// pages/connectDev/connectDev.js
var app = getApp()
var common = require("../../../common/common.js")
var BLELocker = require('../../../common/BLELocker.js')
var commonUtil = require('../../../utils/commonUtil');

//常量数据配置
var ConstantData = require('../../../common/constant_data.js')
var colonyBlue = require("../../../pages/index/colony_blue.js")
var statistic = require("../../../pages/index/statistic.js")
var noDepositLease = require("../../../pages/index/no_deposit_lease.js")
var util = require('../../../utils/util.js');
var connectUtil = require('../../../utils/ble-dfu/connect.js');
import AudioUtil from '../../utils/AudioUtil';


var systemInfo = wx.getSystemInfoSync()
var baseVer = systemInfo.SDKVersion
const user_id = wx.getStorageSync('user_id')
var rfId = null

Page({

  /**
   * 页面的初始数据
   */
  data: {
    equTypeName: '',
    showMaintPlatform: false,
    showUseOtherMini: false,
    platformTipDesc: '',
    //设备使用图示显示为false
    showHelpPicFlg: false,
    //免费时长剩余提醒
    showFreeTipDialog:false,
    showScanTimeoutDialog:false,
    noticeList: [
      '租借中有任何疑问 请联系我们客服',
      '设备租借后请妥善保管，丢失需照价赔偿哦～',
    ],
    // 交易保障标配置
    jybzConfig: {
      pageType: 'goods_detail',
      goodsName: 'e家康护共享轮椅',
      goodsImg: 'https://www.ejiakanghu.cn/images/mini_tip/home_ad_top.png',
      goodsPrice: '租金￥0.00元起',
      align: 'between',
      spaceSize: 12,
      bannerStyle: {
        fontSize: 'mini',
        fontOpacity: 'gray',
      },
    },
    connectType: '租借',
    miniImg: {
      chair_insert_style: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/chair_insert_style.jpg',
      kaoyou: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/kaoyou.png',
      short_box: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/short_box.png',
      long_box: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/long_box.png',
      temp_time_card: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/temp_time_card.jpg',
      use_tip_img_1: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/use-tip-img-1.png',
      use_tip_img_2: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/use-tip-img-2.png',
      use_tip_img_3: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/use-tip-img-3.png',
    },
    showStat: {
      //收费规则
      rule: false,
      //蓝牙/网关连接
      connect: false,
      //按钮连接
      btncon: false,
      //租借成功显示
      leasesuc: false,
      //蓝牙IOS系统授权引导
      bleauthIos: false,
      //蓝牙安卓系统授权引导
      bleauthAndroid: false,
      //蓝牙安卓系统可跳转去打开提示
      bleauthAndroidToSet: false,
      //蓝牙应用权限设置
      bleauthAppToSet: false,
      //蓝牙小程序授权设置
      bleMiniAuthToSet: false,
      //蓝牙应用的定位权限设置
      locationAuthAppToSet: false,
      //IOS系统定位权限提示
      locationIosTip: false,
      //安卓系统定位权限提示
      locationAndroidTip: false,
      //失败提示
      failTip: false,
      //归还成功
      backsuc: false,
      //归还成功后立马租借提示
      backSucToLease: false,
      //结果信息显示
      resultTip: false,
      //展示结果说明信息
      resultDesc: '',
      //苹果蓝牙系统设置视频
      bleIosSysSetVideo: false,
    },
    statVal: {
      //查询免押订单
      queryNoDeposit: "queryNoDeposit",
      //免押成功后开锁
      noDepositOpen: "noDepositOpen",
      //蓝牙搜索中
      discover: "discover",
    },
    read: true,
    showRules: true,
    rulePic: null,
    images: [
      'https://img0.baidu.com/it/u=1411230536,3153397530&fm=26&fmt=auto',
      'https://img2.baidu.com/it/u=3788886525,2387163296&fm=253&fmt=auto&app=120&f=JPEG?w=1203&h=800',
      'https://img1.baidu.com/it/u=2521468805,52921477&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500',
      'https://img2.baidu.com/it/u=2700842424,180930865&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=338'
    ],
    bleIosSysSetHtml: `
        <div><p style="padding: 15px 20px; font-weight: bold;font-size:16px;">请您将手机蓝牙打开，开锁更快哦！</p></div>
          <div><p style="padding: 0px 20px; color:#595959;">向下轻扫屏幕右上方边缘，打开【控制中心】</p></div>
          <div><p style="padding: 0px 20px; color:#595959;">点击蓝牙图标，开启蓝牙功能</p></div>
          <div style="width:100%;text-align::center;margin-top:15px;"><img src="http://minio.ejiakanghu.cn/lbb-erp/temp/打开蓝牙--iOS（压缩）_1692005223345.gif" style="height:167px; display: block;margin:0 auto;"/></div>
        `,
        bleIosSysSetHtml13: `
        <div><p style="padding: 15px 20px; font-weight: bold;font-size:16px;">第1步:请您将微信蓝牙权限打开</p></div>
          <div style="width:100%;text-align::center;margin-top:15px;"><img src="http://minio.ejiakanghu.cn/lbb-erp/temp/IMG_32203x_1692008483798.png" style="height:167px; display: block;margin:0 auto;"/></div>
          <div><p style="padding: 15px 20px; font-weight: bold;font-size:16px;margin-top:15px;">第2步:重新启动微信App，扫码使用</p></div>
        `,
    bleIosSysSetHtml2: `
        <div style="padding: 15px 20px;display:inline-block;vertical-align:middle;"><img src="https://www.ejiakanghu.cn/images/mini_tip/dot_tip.png" style="float:left;" /><p style="margin:auto;float:left;font-weight: bold;margin-left:10px;padding-top:2px;">您好像还没有尝试打开，跟着我一起哦</p></div>
        <img src="https://www.ejiakanghu.cn/images/mini_tip/ble_ios_sys_set2.png" style="width:100%; height:auto; display: block;"/>
      `,
    bleAndroidSysSetHtml: `
          <p style="padding: 15px 20px; font-weight: bold;">1、打开设置（通常为小齿轮图标）</p>
          <img src="https://www.ejiakanghu.cn/images/mini_tip/android_xiaomi_sys_set.png" style="width:100%; height:auto; display: block; border:1px solid grey;"/>
          <p style="padding: 15px 20px; font-weight: bold;">2、根据图示打开系统的蓝牙权限</p>
          <img src="https://www.ejiakanghu.cn/images/mini_tip/android_xiaomi_sys_ble.png" style="width:100%; height:auto; display: block; border:1px solid grey;"/>          
    `,
    bleauthAndroidToSetHtml: `
         <div><p style="padding: 15px 20px; font-weight: bold;font-size:16px;">请您将手机蓝牙打开，开锁更快哦！</p></div>
         <div><p style="padding: 0px 20px; color:#595959;">向下轻扫屏幕，打开【控制中心】</p></div>
         <div><p style="padding: 0px 20px; color:#595959;">点击蓝牙图标，开启蓝牙功能</p></div>
         <div style="width:100%;text-align::center;margin-top:15px;"><img src="http://minio.ejiakanghu.cn/lbb-erp/temp/打开蓝牙和定位-安卓（压缩）_1692005594715.gif" style="height:260px; display: block;margin:0 auto;"/></div>        
    `,
    locationIosToSetHtml: `
        <div><p style="padding: 15px 20px; font-weight: bold;font-size:16px;">请您将手机定位打开,开锁更快哦！</p></div>
        <div><p style="padding: 0px 20px; color:#595959;">打开【设置】</p></div>
        <div><p style="padding: 0px 20px; color:#595959;">找到【隐私与安全性】，打开定位服务</p></div>
        <div style="width:100%;text-align::center;margin-top:15px;"><img src="http://minio.ejiakanghu.cn/lbb-erp/temp/打开系统定位（压缩）_1692428542114.gif" style="height:150px; display: block;margin:0 auto;"/></div>        
    `,
    locationAndroidSetHtml: `
    <p style="padding: 15px 20px; font-weight: bold;">下滑屏幕点亮位置权限图标</p>
    <img src="https://www.ejiakanghu.cn/images/mini_tip/android_xiaomi_sys_location.png" style="width:100%; height:auto; display: block; border:1px solid grey;"/>    
    `,
    locationAndroidAppToSetHtml: `
          <p style="padding: 15px 20px; font-weight: bold;">1.打开设置</p>
          <img src="https://www.ejiakanghu.cn/images/mini_tip/android_xiaomi_app_auth_set.png" style="width:100%; height:auto; display: block; border:1px solid grey;"/>
          <p style="padding: 15px 20px; font-weight: bold;">2.设置定位权限为"仅在使用中允许"</p>
          <img src="https://www.ejiakanghu.cn/images/mini_tip/android_xiaomi_app_localtion_set.png" style="width:100%; height:auto; display: block; border:1px solid grey;"/>          
    `,
    locationIosAppToSetHtml: `
    <p style="padding: 15px 20px; font-weight: bold;">设置位置权限为"使用APP期间"</p>
    <img src="https://www.ejiakanghu.cn/images/mini_tip/ios_app_location.png" style="width:100%; height:auto; display: block; border:1px solid grey;"/>    
    `,
    bleIosAppToSetHtml: `
    <p style="padding: 15px 20px; font-weight: bold;">根据图示打开蓝牙权限"</p>
    <img src="https://www.ejiakanghu.cn/images/mini_tip/ios_app_ble.png" style="width:100%; height:auto; display: block; border:1px solid grey;"/>    
    `,
    blueMiniToSetHtml: `
    <p style="padding: 15px 20px; font-weight: bold;">要去设置小程序蓝牙权限为"仅在使用小程序期间"</p>
    <img src="https://www.ejiakanghu.cn/images/mini_tip/android_xiaomi_mini_blue_set.png?v=1.0" style="width:100%; height:auto; display: block; border:1px solid grey;"/>    
    `,
    locationAppToSetHtml: '',
    depositAutoBack: false,
    isScanBack: false,
    refund: 0,
    userInfoStr: '',
    wxScore: 600,
    leaseBtnShow: false,
    selBindUserId: 0, //选择的绑定的用户id
    isReturn: false,
    modal: {
      modal_show: false
    },
    //支付押金按钮是否可点击，true可以点击，false不可以点击
    payDepositBtnStatus: true,
    //用户手机信息
    phoneInfo: '',
    openLockStat: false,
    bleIosRetryBtnName: '开启后，点击重试',
    //是否点击去查看协议 
    isToViewProtocol: false,
    //是否跳转到租借成功页面
    isToTipBackSucPage: false,

    // 新弹框
    isReturnTip:'',
    isContinueLease:'您是还要继续租借吗？',
    secondSureLeaseState:false,
    checked:false,
    sureState:false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    leaseShow.pageThat = this
    bleAuthShow.pageThat = this
    bleFailShow.pageThat = this
    connectShow.pageThat = this
    conTimer.pageThat = this
    connectUtil.connectShowFunc = connectShow
    connectUtil.setConShowViewCallback(this.conShowInfo)
    app.globalData._that = this
    let that = this
    that.data.phoneInfo = systemInfo.brand + systemInfo.model
    let qrc = unescape(options.qrc)
    let type = options.type
    this.data.depositAutoBack = options.depositAutoBack
    this.data.isScanBack = options.isScanBack
    let systeminfo = wx.getStorageSync('systeminfo')
    console.log('systeminfo------------>', systeminfo)
    let boxHeight = systeminfo.windowHeight*2*0.85>700 ? 700 :systeminfo.windowHeight*2*0.85
    let windowHeight = systeminfo.windowHeight*2-boxHeight
    let nextHeight = windowHeight-282
    this.setData({
      userInfoStr: 'U' + user_id + '-wx' + ConstantData.CONSTATNT_DATA.MINI_VERSION,
      wxScore: options.wxScore,
      connectType: options.connectType,
      windowHeight:windowHeight,
      nextHeight: nextHeight
    })
    this.data.qrc = qrc
    this.data.type = type
    that.getDevIdAndConnect(qrc, type);
  },

  changeChecked() {
    const vm = this
    vm.setData({
      checked: !vm.data.checked,
      sureState:false
    })
  },
  checkboxChange: function(e) {
    this.data.checkedVal = e.detail.value
    this.setData({
      checked: !this.data.checked,
      sureState:false
    })    
  },

  prevent() {},
  
  returnIndex: function() {
    wx.reLaunch({ 
      url: '/pages/index/index',
    })
  },

  isSureContinueLease:function() {
    this.setData({
        secondSureLeaseState:true,
        checked:false,
        sureState:false
    })
  },

  secondSureLease:function() {
    if (!this.data.checked) {
        this.setData({
            sureState:true
        })
    } else if (this.data.checked) {
        this.setData({
            sureState:false,
            secondSureLeaseState:false,
            isReturn:false
        })
        this.continueToLease()
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    this.data.isToViewProtocol = false
    this.data.isToTipBackSucPage = false
    clearTimeout(this.data.hideDisConTimer)
    clearTimeout(that.data.queryNoDepositTimer)
    clearInterval(that.data.checkPayStatusInterval);
     
    commonUtil.getMiniSetting(baseVer)
    systemInfo = wx.getSystemInfoSync()
    baseVer = systemInfo.SDKVersion
		let platform = systemInfo.platform.toLowerCase()
    that.setData({
      locationAppToSetHtml: platform == 'ios' ? that.data.locationIosAppToSetHtml : that.data.locationAndroidAppToSetHtml
    })
    // mark: onShow 权限再次检验
    if (this.data.showStat.bleauthIos || this.data.showStat.bleauthAndroid || this.data.showStat.bleauthAndroidToSet) {
      console.log("onShow-系统蓝牙权限未打开")
      //当前系统蓝牙权限未打开   
      that.setData({
        conLeftSeconds: 0
      })
      that.data.checkSysBleCount = 0;
      connectShow.checkBle()
      var checkSysBleTimer = setInterval(function () {
        that.data.checkSysBleCount++;
        let isAuth = commonUtil.validateBleAuth()
        console.log("蓝牙权限校验结果:", isAuth, that.data.checkSysBleCount)
        let isOpenBle = isAuth != 'sys_ble_android' && isAuth != 'sys_ble_ios'
        if (isOpenBle || that.data.checkSysBleCount > 5) {
          that.getDevIdAndConnect(that.data.qrc, that.data.type);
          clearInterval(checkSysBleTimer);
        }
      }, 1000)
    } else if (this.data.showStat.bleauthAppToSet) {
      console.log("onShow-蓝牙应用权限未打开")
      //蓝牙应用权限未打开
      that.getDevIdAndConnect(this.data.qrc, this.data.type);
    } else if (this.data.showStat.bleMiniAuthToSet) {
      console.log("onShow-小程序蓝牙权限未打开")
      //蓝牙应用权限未打开
      that.getDevIdAndConnect(this.data.qrc, this.data.type);
    } else if (this.data.showStat.locationAuthAppToSet) {
      console.log("onShow-定位应用权限未打开")
      //定位应用权限未打开
      that.getDevIdAndConnect(this.data.qrc, this.data.type);
    } else if (this.data.showStat.locationIosTip || this.data.showStat.locationAndroidTip) {
      console.log("onShow-定位系统权限未打开")
      //定位系统权限未打开
      that.getDevIdAndConnect(this.data.qrc, this.data.type);
    }

    let devIsCon = app.globalData.devConnected;
    console.log("conDevPage onShow :", devIsCon, app.globalData.isOpenLock)
    if (devIsCon && app.globalData.isOpenLock) {
      noDepositLease.getLeaseNoDepositInfo(app.globalData.appOnShowData, that);
    }
  },

  //重试连接
  retryCon: function (e) {
    let that = this
    console.log("retryCon---->", e)
    let conType = e.currentTarget.dataset.contype

    let miniVideoIsOk = commonUtil.validateMiniVideoApi()
    if (conType == 'bleIosSys') {
      this.setData({
        bleIosSysSetVideo: miniVideoIsOk,
        bleIosSysSetHtml: that.data.bleIosSysSetHtml2,
        bleIosRetryBtnName: "我已开启，重试",
      })
    }
    this.getDevIdAndConnect(this.data.qrc, this.data.type);
  },
  /**
   * // mark: 查看小视频 
   */
  viewMniVideo: function (e) {
    let videoid = e.currentTarget.dataset.videoid
    wx.openChannelsActivity({
      finderUserName: 'sphM5c55kSJZjX2',
      feedId: videoid,
      fail: function (err) {
        console.log("视频号视频打开失败:", err)
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    let that = this
    that.recordBlueConnectError(ConstantData.err_type.page_hide, '连接页面隐藏');
    //防止用户切换程序，再回来继续流程导致失败
    if(that.data.canRetry85) {
      that.data.canRetry85 = false;
      wx.reLaunch({
        url: '/pages/index/index',
      })
      return
    }
    

    if (this.data.isToTipBackSucPage) {
      conTimer.clearConTimer()
    }
    if (!this.data.openLockStat && !app.globalData.isOpenLock) {
      let isConnected = app.globalData.devConnected
      if (!this.data.isToViewProtocol && app.globalData.isConnecting === false) {
        this.data.hideDisConTimer = setTimeout(function(){
          BLELocker.disconnect('condev183');
          if (isConnected && !that.data.isToTipBackSucPage) {
            wx.reLaunch({
              url: '../../../pages/index/index',
            })
          }
        }, 35000)        
      }
    }
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    app.globalData.isConnecting = false
    app.globalData.isOpenLock = false
    app.globalData.isUpgradeing = false
    this.data.openLockStat = false
    clearTimeout(this.data.hideDisConTimer)
    clearTimeout(this.data.queryNoDepositTimer)
    clearInterval(this.data.checkPayStatusInterval);
    BLELocker.disconnect('condev96')
    this.recordBlueConnectError(ConstantData.err_type.page_unload, '连接页退出');
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  // mark: 收费规则协议是否勾选
  proCheckChange: function (e) {
    // const values = e.detail.value
    // if (values.length > 0) {
    //   this.setData({
    //     read: true
    //   })
    // } else {
    //   this.setData({
    //     read: false
    //   })
    // }
    this.setData({
          read: e.detail
        })
  },

  //隐藏全部显示提示模块
  hideAllShow: function () {
    this.setData({
      showStat: {
        //收费规则
        rule: false,
        //蓝牙/网关连接
        connect: false,
        //按钮连接
        btncon: false,
        //租借成功显示
        leasesuc: false,
        //蓝牙IOS系统授权引导
        bleauthIos: false,
        //蓝牙安卓系统授权引导
        bleauthAndroid: false,
        //蓝牙安卓系统可跳转去打开提示
        bleauthAndroidToSet: false,
        //蓝牙应用权限设置
        bleauthAppToSet: false,
        //蓝牙小程序授权设置
        bleMiniAuthToSet: false,
        //蓝牙应用的定位权限设置
        locationAuthAppToSet: false,
        //IOS系统定位权限提示
        locationIosTip: false,
        //安卓系统定位权限提示
        locationAndroidTip: false,
        //失败提示信息
        failTip: false,
        //归还成功
        backsuc: false,
        //归还成功后立马租借提示
        backSucToLease: false,
        //结果信息显示
        resultTip: false,
        //展示结果说明信息
        resultDesc: '',
      },
      modal: {
        modal_show: false
      },
    })
  },

  cleanTimer: function () {
    conTimer.clearConTimer()
  },
  // mark: 获取蓝牙授权显示对象
  getBleAuthShowObj: function () {
    return bleAuthShow
  },
  // mark: 获取连接显示对象
  getConnectShowObj: function () {
    return connectShow
  },
  getBleFailShowObj: function () {
    return bleFailShow
  },
  conShowInfo: function (stat) {
    if (stat == 'auth_mini_ble') {
      bleAuthShow.showBleMiniToSet()
    }
  },

  //点击去打开系统蓝牙权限
  toSetSysBle: function () {
    wx.openSystemBluetoothSetting({
      success(res) {
        console.log("打开系统蓝牙配置", res)
      }
    })
  },
  //点击去打开应用的权限
  toSetAppAuth: function () {
    wx.openAppAuthorizeSetting({
      success(res) {
        console.log(res)
      }
    })
  },
  //去设置小程序权限
  toSetMiniAuth: function () {
    wx.openSetting({
      success(res) {
        console.log(res.authSetting)
        getApp().globalData.miniAuthSetting = res.authSetting
      }
    })
  },
  //弹框取消
  onCancelDialog1: function () {
    this.setData({ showFreeTipDialog: false });
  },

  onConfirmDialog1: function () {
    this.setData({ showFreeTipDialog: false });    
  },
  
  onConfirmDialog3: function () {
    this.setData({ showScanTimeoutDialog: false });
    this.returnIndex()
  },
  //查看使用图示
  viewHelpPic: function() {
     let that = this
     this.setData({
       showHelpPicFlg: !that.data.showHelpPicFlg
     })
  },

  getDevIdAndConnect: function (qrc, type) {
    connectShow.reday()
    //请求获取设备mac
    app.globalData.beforeConIsGateway = false;

    console.log("-----*****************----qrc=" + qrc)
    var that = this;
    that.data.scanningCode = false;
    //初始扫码95重试标记清空
    that.data.retry95Flg = false;
    that.data.canRetry85 = false;
    that.data.canceledConnect = false;
    if (systemInfo && ((systemInfo.model && systemInfo.model.toLowerCase().indexOf('iphone') != -1) || (systemInfo.brand && systemInfo.brand.toLowerCase().indexOf('iphone') != -1)) && systemInfo.system.toLowerCase().indexOf('ios') < 0) {
      systemInfo.system = 'ios' + systemInfo.system;
    }
    var phoneModel = systemInfo ? systemInfo.model : "";
    var phoneType = systemInfo ? systemInfo.brand : "";
    app.globalData.disconnectLineNum = '';
    that.data.reqConDevTime = null;
    app.executeRequest(function (header) {
      console.log('now request device')
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/connect/device',
        method: 'post',
        header: header,
        data: {
          qrc: qrc,
          system: systemInfo.system,
          phoneModel: phoneType, //手机厂商
          phoneType: phoneModel, //手机型号
          isScanBack: that.data.isScanBack,
          lng: that.data.locationLng,
          lat: that.data.locationLat,
          locTime: that.data.locationTime,
        },
        success: function (res) {
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          //校验服务器
          if(!that.data.reqConDevTime) {
            that.data.reqConDevTime = new Date().getTime()
          }else {
            let diff = new Date().getTime() - that.data.reqConDevTime
            if(diff < 5000) {
               wx.showToast({
                  title: '处理中..',
               })
               return
            }
          }
          console.warn("getDev--=====res=", res);
          that.data.qrc = qrc;
          //用于one more陪护椅的开锁状态赋值
          app.globalData.curConMac = that.data.conMac;
          that.data.conDevRes = res
          if (res.data.rst == 10) {
            //用户刚刚租借成功提示,防止用户误操作再次租借            
            common.clearConTimeCountTimer(1522)
            let extP = res.data.extParams
            that.setData({
              beforeLeaseTipTitle: extP && extP.beforeLeaseTipTitle ? extP.beforeLeaseTipTitle : that.data.beforeLeaseTipTitle,
              beforeLeaseTipContent: extP && extP.beforeLeaseTipContent ? extP.beforeLeaseTipContent : that.data.beforeLeaseTipContent,
              beforeLeaseIsContinue: extP && extP.beforeLeaseIsContinue ? extP.beforeLeaseIsContinue : true,
            })
            leaseShow.backSucToLeaseTip()
            return
          }
          if (res.data.rst == 10001) {
              bleFailShow.modalMsgShow()
              let desc = res.data.desc
              console.log('desc======>',desc)
              that.data.scanningCode = false;
              that.setData({
                loading_show: false,
              })
              that.recordBlueConnectError(ConstantData.err_type.qrc_net_rst_err, 'modalErr--qrc=' + qrc + ';res:' + JSON.stringify(res));
              wx.reLaunch({
                url: '../../../pages/index/index?desc=' +desc,
              })
              return
          }

          let isOk = res.data.rst === 0;
          if (!isOk) {
            bleFailShow.modalMsgShow()
            that.data.scanningCode = false;
            let descInfo = res.data.desc ? res.data.desc : '错误编号' + res.data.rst;
            that.setData({
              loading_show: false,
              modal: {
                modal_show: true,
                desc: descInfo,
                confirm: true
              }
            })
            that.recordBlueConnectError(ConstantData.err_type.qrc_net_rst_err, 'modalErr--qrc=' + qrc + ';res:' + JSON.stringify(res));
            return;
          }

          //处理返回数据并调用
          that.handleConDevRes()

        },
        fail: function (res) {
          console.log("根据qrc获取mac名称请求失败", res)
          that.data.scanningCode = false;
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          bleFailShow.modalMsgShow()
          that.setData({
            loading_show: false,
            modal: {
              modal_show: true,
              desc: '请重新扫码-' + ConstantData.err_type.qrc_mac_fail,
              confirm: true
            }
          })
          that.recordBlueConnectError(ConstantData.err_type.qrc_mac_fail, 'modalErr--qrc=' + qrc + ';res:' + JSON.stringify(res));
        }
      })

    })

  },

  /**
   * 处理扫码从服务获取设备信息
   */
  handleConDevRes: function () {
    let that = this
    let res = that.data.conDevRes
    console.log("处理扫码获取的设备信息:", res)
    if (res.data.extParams && res.data.extParams.lockType) {
      that.setData({
        lockType: res.data.extParams.lockType
      })
    }
    that.recordBlueConnectError(ConstantData.err_type.qrc_mac_suc, 'getDevIdAndConnect macId=' + (res.data ? res.data.macId : 'null'));
    //扫码后获取到的连接的mac地址
    that.data.conMac = res.data ? res.data.macId : "";
    that.data.conBlueName = res.data ? res.data.extParams.blueName : "";
		app.globalData.conBlueVer = res.data ? res.data.extParams.blueVer : "";		

		that.startConnect(res);  
  },
  //开始进行蓝牙连接
  startConnect: function (res) {
    var that = this;
    //取消重试
    let netErr = app.handleRes(res, that);
    if (netErr) {
      that.data.scanningCode = false;
      that.setData({
        loading_show: false
      })
      return
    }
    if (res.data.isBindPhone == 0) {
      that.setData({
        phoneAuthStatus: true,
        phoneAuthBtt: 'scan',
        loading_show: false
      });
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      that.data.scanningCode = false;
      return;
    }
    that.setData({
      phoneAuthStatus: false,
      phoneAuthBtt: ''
    });
    app.globalData.curConHid = null;
    if (res.data.hid) {
      that.setData({
        pile_id: res.data.hid
      })
      app.globalData.curConHid = res.data.hid;
      wx.setStorageSync('pileId', res.data.hid);
      that.data.pile_type = res.data.hpVer && res.data.hpVer.indexOf('长') != -1;
    }
    app.globalData.isLeaseCon = false;
    app.globalData.isAllowUpgrade = false;
    app.globalData.isBeforeLeaseUpgrade = false;
    app.globalData.allowUpgradeOtherMac = false;
    app.globalData.isPayUpgrade = false;
    app.globalData.isLockUpgrade = false;
    app.globalData.otherMacs = [];
    that.data.isFirstUseNewConLeaseFlg = false;
    that.data.isSend98Cmd = false;
    that.data.canRetry85 = false;

    if (res.data.extParams) {
      that.data.conDevExtParams = res.data.extParams;
      app.globalData.isAllowUpgrade = res.data.extParams.isAllowUpgrade;
      app.globalData.lastDriveVer = res.data.extParams.lastDriveVer;
      app.globalData.isBeforeLeaseUpgrade = res.data.extParams.isBeforeLeaseUpgrade;
      app.globalData.isPayUpgrade = res.data.extParams.isPayUpgrade;
      app.globalData.isLockUpgrade = res.data.extParams.isLockUpgrade;
      app.globalData.allowUpgradeOtherMac = res.data.extParams.allowUpgradeOtherMac ? res.data.extParams.allowUpgradeOtherMac : false;
      app.globalData.otherMacs = res.data.extParams.otherMacs ? res.data.extParams.otherMacs : [];
      //是否第一次是用新的蓝牙连接方式
      that.data.isFirstUseNewConLeaseFlg = res.data.extParams.isFirstUseNewConLeaseFlg ? res.data.extParams.isFirstUseNewConLeaseFlg : false;
      //是否发送98命令
      that.data.isSend98Cmd = res.data.extParams.isSend98Cmd ? res.data.extParams.isSend98Cmd : false;
      //网关连接超时的时长。默认20秒超时
      app.globalData.gatewayConTimeout = res.data.extParams.gatewayConTimeout ? res.data.extParams.gatewayConTimeout : 20000;
      //网关开锁超时的时长,默认15秒超时
      app.globalData.gatewayUnlockTimeout = res.data.extParams.gatewayUnlockTimeout ? res.data.extParams.gatewayUnlockTimeout : 15000;
      //网关连接失败后多长时间内使用蓝牙重试连接，默认为5分钟内再次扫码可使用蓝牙连接
      app.globalData.gatewayFailBleConTime = res.data.extParams.gatewayFailBleConTime ? res.data.extParams.gatewayFailBleConTime : 30000;
      //蓝牙连接失败后多长时间内使用网关重试连接，默认为5分钟内再次扫码可使用网关连接
      app.globalData.gatewayBleFailConTime = res.data.extParams.gatewayBleFailConTime ? res.data.extParams.gatewayBleFailConTime : 30000;
    }



    //清空定时器
    app.clearTimeoutTimer();
    //清空秘钥
    that.data.blepwd = '';

    app.globalData.startConTime = new Date().getTime();
    that.data.newConFlg = res.data.newConFlg;

    //连接的调用不允许进行升级的操作
    app.globalData.isBeforeLeaseUpgrade = false;
    app.globalData.isLeaseCon = true;
    //扫完码拿到数据执行连接的过程
    that.executeConnect(res);
  },

  //执行蓝牙连接
  executeConnect: function (res) {
    var that = this;
    //清空选择的设备类型
    that.setData({
      selTypeList: [],
    })
    //连接前去除95重试标记
    that.data.retry95Flg = false;
    let pile_id = that.data.pile_id ? 'Z' + that.data.pile_id : '';
    let errType = '';
    let user_no_back = wx.getStorageSync('user_no_back');
    if (res.data.rst == 0 || (res.data.rst == 6 && user_no_back)) {
      var hpStat = res.data.hpStat;
      if (hpStat && hpStat != 0 && hpStat != 1) {
        // var desc = res.data.desc ? res.data.desc : "维护中,请使用其他设备";
        if (user_no_back) {
          errType = ConstantData.err_type.qrc_maintain_back;
          var desc = "归位桩维护中,如您确定设备已锁在桩上拉不下来,请联系客服处理";
          var desc_mini = "桩维护" + pile_id + "(" + that.data.phoneInfo + "-" + errType + ")";
          var contact = true;
          var confirm = false;
        } else {
          errType = ConstantData.err_type.qrc_maintain_rent;
          var desc = res.data.desc ? res.data.desc : "归位桩维护中,请换其它桩租赁";
          var desc_mini = "桩维护" + pile_id + "(" + that.data.phoneInfo + "-" + errType + ")";
          var contact = false
          var confirm = true
        }
        bleFailShow.modalMsgShow()
        //归位桩存在问题
        that.setData({
          loading_show: false,
          modal: {
            modal_show: true,
            desc: desc,
            desc_mini: desc_mini,
            open_location_show: false,
            retryConnect: false,
            retry95: false,
            confirm: confirm,
            contact: contact
          }
        })
        that.recordBlueConnectError(errType, 'modalErr:归还失败');
        that.data.scanningCode = false;
        return;
      }

      var name = res.data.macId;
      if (name == null || name == '') {
        console.log("根据qrc获取mac名称为空")
        errType = ConstantData.err_type.qrc_mac_null;
        bleFailShow.modalMsgShow()
        that.setData({
          loading_show: false,
          modal: {
            modal_show: true,
            desc: '请重新扫码-' + errType,
            confirm: true
          }
        })
        that.recordBlueConnectError(errType, 'modalErr:获取mac为空');
        that.data.scanningCode = false;
        return
      }
      var deviceId = res.data.deviceId

      let isExtBlueName = that.data.conBlueName && that.data.conBlueName.indexOf("DK") == -1;
      let conBlueName = isExtBlueName ? that.data.conBlueName : "DK" + name;
      that.setData({
        loading_show: true,
        loading_desc: '开始连接...',
        agentLeaseSelStatus: false,
        showModalStatus: false,
        wxDeviceId: deviceId, //数据库存储的公众号获取的设备id
        curBlueName: conBlueName,
        isNoRfidOpen: res.data.isNoRfidOpen,
        isJudgeInsertSwitch: res.data.judgeInsertSwitch,
        isBackChairStatus: res.data.backStat,
        curIsDirectCon: res.data.curIsDirectCon
      })

      setTimeout(function () {
        that.data.scanningCode = false;
      }, 1000);

      app.globalData.isAllowBroadcastBack = res.data.isAllowBroadcastBack;

      //蓝牙集群节点判断处理
      //是否存在蓝牙节点
      var colonyIsExists = res.data.colonyIsExists;
      //集群节点是否在使用中0未占用,1被占用
      var colonyIsUsing = res.data.colonyIsUsing;
      //是否直接使用蓝牙节点连接
      var hpIsColony = res.data.hpIsColony;
      that.data.hpIsColony = hpIsColony;
      //是否可直接使用节点
      var colonyIsDirectUse = hpIsColony == 1 && colonyIsUsing == 0 && colonyIsExists == 1;

      console.log("是否直接网关连接:", colonyIsDirectUse);

      let firstConFail = colonyBlue.isBleFailGatewayCon();
      console.log("是否首次蓝牙连接失败:", firstConFail);
      //是否在连接失败后使用
      var colonyIsFailUse = hpIsColony == 2 && colonyIsUsing == 0 && colonyIsExists == 1;
      if (colonyIsFailUse && firstConFail) {
        colonyIsDirectUse = true;
        that.setData({
          colonyConFail: 0
        })
      }

      that.data.noBackEqId = res.data.extParams.noBackEqId;
      //网关连接失败后5分钟内扫码，改用蓝牙连接
      let isBleCon = colonyBlue.isGatewayFailBleCon();
      console.log("是否首次网关连接失败:", isBleCon);
      if (!isBleCon && colonyIsDirectUse && that.data.colonyConFail < 3) {
        //开锁前判断是否是蓝牙集群的连接
        that.data.mac = name
        that.data.colonyIsExists = colonyIsExists
        common.storeGatewayClientType();
        console.log("开始直接连接蓝牙集群---->");
        //直接使用蓝牙集群连接
        colonyBlue.connectDev(name, that);
        return;
      }

      if (that.data.pt == 'blue_tip') {
        that.data.pt = '';
      }

      //非网关的使用wxmini
      common.storeWxClientType(that);
      //进行蓝牙连接
      that.data.timeout95RetryFlg = true; //连接后95超时可以进行一次重连
      that.data.retryCon = false; //刚开始还没有进行重试点击
      that.connectBLEDevice(conBlueName);
    } else if (res.data.rst == 6) { //共享陪护床
      bleFailShow.modalMsgShow()
      that.setData({
        modal: {
          modal_show: true,
          desc: that.data.conDevExtParams && that.data.conDevExtParams.close_tip ? that.data.conDevExtParams.close_tip : "当前时间不可租借",
          confirm: true
        }
      })
      that.data.scanningCode = false;
    } else {
      errType = ConstantData.err_type.qrc_mac_rst;
      bleFailShow.modalMsgShow()
      that.setData({
        modal: {
          modal_show: true,
          desc: '请重新扫码-' + errType,
          confirm: true
        }
      })
      that.data.scanningCode = false;
      console.log("根据qrc获取mac请求返回值非0：" + res.data.rst)
      that.recordBlueConnectError(errType, 'modalErr--qrc=' + that.data.qrc + '--' + res.data.rst);
    }

  },
  // mark: 检查连接的蓝牙相关权限
  bleConAuthCheck: function (isCheckLocation) {
    //第一使用蓝牙连接，检查蓝牙连接权限
    let isAuth = commonUtil.validateBleAuth()
    console.log("蓝牙权限校验结果:", isAuth)
    if (isAuth == 'sys_ble_android') {
      //系统蓝牙未打开跳转到对应页面
      bleAuthShow.showAndroidToSettingBle()
      return 1
    } else if (isAuth == 'sys_ble_ios') {
      bleAuthShow.showIosSetBleTip()
      return 1
    } else if(isCheckLocation){
      if (isAuth == 'sys_location') {
        //跳转到系统定位权限        
        if (systemInfo.platform == 'ios') {
          //苹果系统
          bleAuthShow.showIosSysLocationSetting()
        } else {
          bleAuthShow.showAndroidSysLocationSetting()
        }
        return 1
      } else if (isAuth == 'wx_location') {
        bleAuthShow.showAppLocationSetting()
        return 1
      }
    } else if(isAuth == 'wx_ble') {
      bleAuthShow.showAppBleSetting()
      return 1
    } else if (isAuth == 'mini_ble') {
      bleAuthShow.showBleMiniToSet()
      return 1
    }
    return 0
  },

  //连接蓝牙设备
  connectBLEDevice: function (blueName) {
    getApp().hideLoading()
    var that = this;

    //测试
    // that.data.curIsDirectCon = true
    let platform = systemInfo.platform.toLowerCase()
    app.globalData.platform = platform
    let isCheckLocation = false
    //是否是安卓系统
    if(that.data.curIsDirectCon && platform == 'android') {
         //安卓系统采取直连，兼容之前版本
         that.data.isFirstUseNewConLeaseFlg = false  
         //检查是否标记不能使用直连方式
         let directConForbidden = wx.getStorageSync('direct_con_forbidden')
         let directConSuc = wx.getStorageSync('direct_con_suc')         
         if(!directConSuc && directConForbidden == 1) {
           //禁止直连
           that.data.isFirstUseNewConLeaseFlg = true
           that.data.curIsDirectCon = true
           isCheckLocation = true
         }
    }    

    let isGatewayConFlg = colonyBlue.isGatewayCon(that);
    if (isGatewayConFlg) {
      //是否蓝牙方式连接
      that.data.curContIsBle = false
      console.log("开始网关连接", blueName)
      that.setData({
        loading_show: true,
        loading_desc: '网关连接准备中...',
        connectDesc: "网关连接准备中...",
      });
      colonyBlue.connectDev(blueName.replace("DK", ""), that);
      return;
    } else {
      that.data.curContIsBle = true
      //使用蓝牙连接检查蓝牙相关权限
      console.log("miniAuth:", app.globalData.miniAuthSetting)
      let rst = that.bleConAuthCheck(isCheckLocation)
      if (rst > 0) {
        return
      }
    }

    common.storeWxClientType(that);

    console.log("connecting...." + blueName)
    that.data.canceledConnect = false;

    //连接开始准备
    connectShow.start();
    that.data.mac = blueName.replace("DK", "")
    that.data.startConTime = new Date().getTime()

    BLELocker.setErrorCallback(function (errType, errDesc) {
      that.recordBlueConnectError(errType, errDesc)
    })
    BLELocker.setConnectLogCall(function (data) {})

    var timebyte = null;
    var encryptval = null;

    //关闭心跳定时器
    if (that.data.bleHeartTimer) {
      clearInterval(that.data.bleHeartTimer);
      console.log("连接前关闭之前的心跳定时器");
    }
    app.globalData.conIsSuc = false;
    app.globalData.upgradeMac = blueName;
    app.globalData.startConTime = new Date().getTime();
    //是否开锁中
    app.globalData.isOpenLock = false;
    app.globalData.isUpgradeing = false;

    //连接中标记
    app.globalData.isConnecting = true;
    //当前连接的mac
    that.data.mac = blueName.replace('DK', '');
    //连接前清空上一次扫码的设备记录
    BLELocker.setDevice(null);
		that.data.blueName = blueName;
    //是否搜的onBluetoothDeviceFound响应超时
    app.globalData.isFindTimeout = false;		

    app.globalData.isDirectConnect = false;
    clearInterval(app.globalData.directConnectTimer)

    if (that.data.isFirstUseNewConLeaseFlg) {
      console.log("使用新连接进行连接");
      //非直接连接
      app.globalData.isDirectConnect = false;
      app.globalData._that.data.openBlueAdapterFail = false;
      app.globalData.isLeaseCon = true;
      BLELocker.setParams(function (status, data) {
        that.handleStatus(status, data)
      }, that);
      connectUtil.startCon(blueName);
      let isWxScan = that.data.isWxScanFlg ? "wxScan" : "ejiaScan";
      if (that.data.canRetry85) {
        isWxScan = isWxScan + ':retry85Con';
      }
      that.recordBlueConnectError(ConstantData.err_type.new_con, 'new connect 1.0 start:' + isWxScan);
    } else if (that.data.curIsDirectCon) {
      console.warn("蓝牙直连-----》")
      app.globalData.isDirectConnect = true;
      app.globalData._that.data.openBlueAdapterFail = false;
      app.globalData.isLeaseCon = true;
      that.recordBlueConnectError(ConstantData.err_type.connect_direct_start, 'directConnect start');
      BLELocker.setParams(function (status, data) {
        that.handleStatus(status, data)
      }, that);
      connectUtil.directBleCon(blueName, that.data.wxDeviceId) 
      // BLELocker.directConnect(blueName, function (status, data) {
      //   that.handleStatus(status, data)
      // }, 0, false, encryptval, timebyte, that);
    } else if (that.data.newConFlg) {
      console.log("蓝牙新连接方式：", blueName)
      //使用新的连接
      app.globalData.isDirectConnect = false;
      BLELocker.newConnect(blueName, function (status, data) {
        that.handleStatus(status, data)
      }, 0, false, encryptval, timebyte, that);
    } else {
      console.log("蓝牙旧连接方式：", blueName)
      app.globalData.isDirectConnect = false;
      BLELocker.connect(blueName, function (status, data) {
        that.handleStatus(status, data)
      }, 0, false, encryptval, timebyte, that) //设置超时时间time,0使用默认的超时时间
    }

    //记录桩的服务信息
    BLELocker.setCollectionServiceData(function (uuid, fce7, fce8, fce9) {
      console.log('暂不记录状服务信息');
    })

  },

  //处理设备连接状态变化回调
  handleStatus: function (status, data) {
    var that = this
    console.log('我就是_Callback', status, data)
    let pile_id = that.data.pile_id ? 'Z' + that.data.pile_id : '';
    if (status == BLELocker.Status.ble01Data) {
      console.log("---新固件驱动连接成功...", data);
      //连接成功数据读取中
      connectShow.read();
      //新固件会主动上报95数据
    } else if (status == BLELocker.Status.bleScanStart) {
      connectShow.discover()
    } else if (status == BLELocker.Status.appVersionNotSupported) {
      getApp().hideLoading()

      //1.关闭正在连接的提示对话框 2.弹出提示用户APP版本太低不支持的对话框
      leaseShow.resultShow("微信APP版本太低不支持")

    } else if (status == BLELocker.Status.bleIsClosed) {
      getApp().hideLoading()
      let systemInfo = wx.getStorageSync('systeminfo');
      if (systemInfo.system && systemInfo.system.toLowerCase().indexOf('ios 13') != -1) {
        bleFailShow.modalMsgShow()
        that.setData({
          openning_show: false,
          loading_show: false,
          modal: {
            modal_show: true,
            icon_name: 'icon-lanya',
            desc: '请在系统设置中打开微信的蓝牙权限后重试',
            desc_center: true,
            desc_mini: 'BT权限不成功' + pile_id + '(' + that.data.phoneInfo + '-100310)',
            open_ble_auth_show: true,
          }
        })
        that.recordBlueConnectError(100310, "modalErr:ios13-蓝牙未打开");
      } else {
        bleFailShow.modalMsgShow()
        that.setData({
          openning_show: false,
          loading_show: false,
          modal: {
            modal_show: true,
            desc_mini: 'BT未打开' + pile_id + '（' + that.data.phoneInfo + '-100311)',
            desc: '请打开蓝牙后重试', //此处的文字在wxml页面有用到，如果变更的话wxml也要同步变更
            retryConnect: true
          }
        })
        that.recordBlueConnectError(100311, "modalErr:蓝牙未打开");
      }
    } else if (status == BLELocker.Status.adaperOpenFail) {
      getApp().hideLoading()
      wx.stopBluetoothDevicesDiscovery({
        success: function (e) {
          console.log(e);
        },
        complete: function (i) {
          console.log(i);
        }
      });
      wx.closeBLEConnection({
        deviceId: that.data.wxDeviceId,
        success: function (res) {
          console.log("close suc", res)
        },
        fail: function (res) {
          console.log("close err", res);
        }
      });
      wx.closeBluetoothAdapter({
        success: function (res) {
          console.log("closeA suc", res)
        },
        fail: function (res) {
          console.log("closeA err", res);
        }
      })
      if (that.data.curIsDirectCon) {
        app.globalData.isDirectConnect = true;
        that.setData({
          loading_desc: '正在自动重连...'
        })
        console.warn('连接失败,正在自动重连');
        BLELocker.directConnect(that.data.blueName, function (status1, data1) {
          that.handleStatus(status1, data1)
        }, 0, false, null, null, that);
        that.recordBlueConnectError(40010, 'directConnect start-adaperOpenFail:' + app.globalData.conErrDesc);
      } else {
        app.globalData.isDirectConnect = false;
        bleFailShow.modalMsgShow()
        that.setData({
          openning_show: false,
          loading_show: false,
          modal: {
            modal_show: true,
            desc_mini: 'BT调起不成功' + pile_id + '（' + that.data.phoneInfo + '-100312)',
            desc: '请关闭蓝牙再打开后重试',
            retryConnect: true
          }
        })
        that.recordBlueConnectError(100312, "modalErr:初始化蓝牙适配器失败");
      }

    } else if (status == BLELocker.Status.bleNotSupportWXService || status == BLELocker.Status.bleNotSupportWXCharacteristic) {
      getApp().hideLoading()

      //1.关闭正在连接的提示对话框 2.弹出提示用户扫描的设备不支持微信协议（其实就是扫描了不支持微信协议连接的设备）
      leaseShow.resultShow("系统版本低,可能无法完成租赁")
    } else if (status == BLELocker.Status.bleReceiveAuthData) {
      getApp().hideLoading()

      //1.将正在连接的提示对话框中的提示语,变更为：连接成功,读取数据中,提示语请自行修改,这个时候正在发送95指令
      that.setData({
        loading_desc: "连接成功,数据读取中",
        loading_show: true
      });

    } else if (status == BLELocker.Status.bleConnectTimeout) {
      getApp().hideLoading()
      wx.stopBluetoothDevicesDiscovery({
        success: function (e) {
          console.log(e);
        },
        complete: function (i) {
          console.log(i);
        }
      });
      wx.closeBLEConnection({
        deviceId: that.data.wxDeviceId,
        success: function (res) {
          console.log("close suc", res)
        },
        fail: function (res) {
          console.log("close err", res);
        }
      });
      wx.closeBluetoothAdapter({
        success: function (res) {
          console.log("closeA suc", res)
        },
        fail: function (res) {
          console.log("closeA err", res);
        }
      })
      var errCode = getTimeoutReasonCode();
      if (that.data.curIsDirectCon) {
        app.globalData.isDirectConnect = true;
        that.setData({
          loading_desc: '正在自动重连...'
        })
        console.warn('连接失败,正在自动重连');
        BLELocker.directConnect(that.data.blueName, function (status1, data1) {
          that.handleStatus(status1, data1)
        }, 0, false, null, null, that);
        return;
      }
      app.globalData.isDirectConnect = false;
      that.recordBlueConnectError(20003, "connect timeout:" + app.globalData.conErrDesc);

      //标记存储蓝牙连接失败的 时间
      colonyBlue.bleConFailMark();
      //1.关闭正在连接的提示对话框 2.弹出提示用户连接设备超时,重新扫码
      that.setData({
        loading_show: false,
        openning_show: false,
      })

      console.log('监听到bleConnectTimeout', errCode);

      if (errCode == '10039') {
        bleFailShow.modalMsgShow()
        that.setData({
          modal: {
            modal_show: true,
            desc: '请关闭蓝牙再打开后重试',
            desc_mini: 'receiveData不成功' + pile_id + '(' + that.data.phoneInfo + '-10039)',
            retryConnect: true
          }
        })
        that.recordBlueConnectError(10039, 'modalErr:接收数据时超时或报错');
      } else if (errCode == '100310') {
        bleFailShow.modalMsgShow()
        that.setData({
          modal: {
            modal_show: true,
            icon_name: 'icon-lanya',
            desc: '请在系统设置中打开微信的蓝牙权限后重试',
            desc_center: true,
            desc_mini: 'BT权限不成功' + pile_id + '(' + that.data.phoneInfo + '-100310)',
            open_ble_auth_show: true,
          }
        })
        that.recordBlueConnectError(100310, 'modalErr:ios13-蓝牙未打开');
      } else if (errCode.indexOf('10034') != -1) {
        getBLETimeoutReasonType(that);
      } else {
        bleFailShow.modalMsgShow()
        that.setData({
          modal: {
            modal_show: true,
            desc: "请关闭蓝牙再打开后重试",
            icon_name: 'icon-lanya',
            desc_mini: 'BT调起不成功' + pile_id + '(' + that.data.phoneInfo + '-' + errCode + ')',
            desc_center: true,
            retryConnect: true
          }
        })
        that.recordBlueConnectError(errCode, 'modalErr:连接超时');
      }

      app.sendLog();
    } else if (status == BLELocker.Status.bleClosed) {
      getApp().hideLoading()

      //1.关闭正在连接的提示对话框（如果当前不是正在连接,是已经弹出租凭开锁对话框,则可以关闭租凭开锁对话框） 2.弹出提示用户蓝牙关闭,请重新扫码
      if (that.data.showModalStatus) {
        that.setData({
          showModalStatus: false,
          mapShowStatus: true,
        })
      }
      //1.关闭正在连接的提示对话框 2.弹出提示用户手机蓝牙未打开
      bleFailShow.modalMsgShow()
      that.setData({
        openning_show: false,
        loading_show: false,
        modal: {
          modal_show: true,
          desc: '蓝牙已关闭,重新打开扫码重试',
          confirm: true
        }
      })
    } else if (status == BLELocker.Status.bleOpened) {
      getApp().hideLoading()
      // wx.showToast({
      //   title: '手动打开蓝牙',
      // })

      //这里不需要做任何处理

    } else if (status == BLELocker.Status.bleSend85Timeout) { //暂未开启
      getApp().hideLoading()
      // wx.showToast({
      //   title: '发送85超时',
      // })

      bleFailShow.modalMsgShow()
      //1.关闭租凭开锁提示对话框 2.提示用户开锁超时,请重新扫码
      that.setData({
        showModalStatus: false,
        loading_show: false,
        mapShowStatus: true,
        openning_show: false,
        openLockLeaseOptStatus: true,
        modal: {
          modal_show: true,
          desc: '开锁超时,扫码归还后重试',
          desc_mini: 'send85Timeout' + pile_id + '-' + ConstantData.err_type.data_85_send_timeout,
          comfirm: true
        },
      });
      that.clear85Timer();
      that.recordBlueConnectError(ConstantData.err_type.data_85_send_timeout, 'modalErr:发送85超时' + ":" + app.globalData.devConnected);
    } else if (status == BLELocker.Status.ble85Back1Timeout) {
      getApp().hideLoading()
      app.globalData.isOpenLock = false;
      app.globalData.isConnecting = false;
      that.data.openLockStat = false; //当前已开锁完毕
      that.recordBlueConnectError(ConstantData.err_type.data_85_back1_timeout, "85第1次回执超时,设备:mac=" + that.data.mac + ":" + app.globalData.devConnected)
      if (!app.globalData.devConnected) {
        that.clear85Timer();
        //重试开锁
        that.retry85('auto');
      } else if (that.data.hasOrderFlg && that.data.no_eject_flg || that.data.no_eject_back_flg == 1 || that.data.no_eject_flg) {
        let descMini = pile_id + '-' + ConstantData.err_type.data_85_back1_timeout_noeject_inner;
        statistic.noEjectDialog(that, descMini);
        that.recordBlueConnectError(ConstantData.err_type.data_85_back1_timeout_noeject_inner, '85第一条回执超时，显示“未弹出弹框”');
      } else {
        let descMini = '85backTimeout' + pile_id + '-' + ConstantData.err_type.data_85_back1_timeout_else;
        statistic.noEjectDialog(that, descMini);
        that.recordBlueConnectError(ConstantData.err_type.data_85_back1_timeout_else, 'modalErr:85第一条回执超时,请扫码归还后重试');
      }
      app.sendLog();
    } else if (status == BLELocker.Status.ble85Back2Timeout) {
      getApp().hideLoading()

      that.recordBlueConnectError(ConstantData.err_type.data_85_back2_timeout, "85第2次回执超时,显示“未弹出弹框”,设备mac=" + that.data.mac)
      that.data.openLockStat = false; //当前已开锁完毕
      app.globalData.isOpenLock = false;
      app.globalData.isConnecting = false;
      let descMini = pile_id + '-' + ConstantData.err_type.data_85_back2_timeout_noeject_inner;
      statistic.noEjectDialog(that, descMini);

    } else if (status == BLELocker.Status.bleSend95Timeout) {
      getApp().hideLoading()
      if (that.data.curBlueName && that.data.timeout95RetryFlg) {
        that.data.timeout95RetryFlg = false;
        that.data.retryCon = false; //刚开始还没有进行重试点击
        that.recordBlueConnectError(ConstantData.err_type.new_conf_95_timeout, '95发送超时,重新连接');
        //收到超时后，重置参数及关闭适配器等需要时间
        setTimeout(function () {
          that.connectBLEDevice(that.data.curBlueName);
        }, 250);
        return;
      }

      //标记存储蓝牙连接失败的 时间
      colonyBlue.bleConFailMark();
      bleFailShow.modalMsgShow()
      //1.关闭正在连接的提示对话框 2.弹出提示用户连接设备失败,重新扫码
      that.setData({
        showModalStatus: false,
        mapShowStatus: true,
        loading_show: false,
        modal: {
          modal_show: true,
          desc_mini: '95超时' + pile_id + '-' + ConstantData.err_type.data_95_send_timeout,
          desc: '连接失败,扫码重试',
          confirm: true
        }
      })

      that.recordBlueConnectError(ConstantData.err_type.data_95_send_timeout, 'modalErr:95超时');
      app.sendLog();
    } else if (status == BLELocker.Status.bleRecive95Timeout || status == BLELocker.Status.bleReciveAuto95Timeout) {

      //标记存储蓝牙连接失败的 时间
      colonyBlue.bleConFailMark();
      bleFailShow.modalMsgShow()
      //1.关闭正在连接的提示对话框 2.弹出提示用户连接设备失败,重新扫码
      that.setData({
        showModalStatus: false,
        mapShowStatus: true,
        loading_show: false,
        modal: {
          modal_show: true,
          desc_mini: '95接收超时' + pile_id + '-' + ConstantData.err_type.new_conf_95_receive_timeout,
          desc: '连接失败,扫码重试',
          confirm: true
        }
      })

      that.recordBlueConnectError(ConstantData.err_type.new_conf_95_receive_timeout, '95数据超时:' + status);

    } else if (status == BLELocker.Status.ble85Data || status == BLELocker.Status.ble88Data) {
      leaseShow.resultShow('开锁命令发送成功')

      that.data.isRetry85 = false;
      app.globalData.isOpenLock = false;
      //开锁完成隐藏可关闭蓝牙
      app.globalData.isConnecting = false;
      //隐藏可以关闭蓝牙
      that.data.hideIsDisconnectStat = true;
      that.recordBlueConnectError(ConstantData.err_type.data_85_suc, "85回执data-" + JSON.stringify(data))
      console.warn('---收到85', data);

      if (that.data.blankPileOpenFlg) {
        //非空桩开锁的可以跳转到开锁结果提示页面
        console.log("空桩开锁完成，不进行跳转")
        return;
      }
      //191101及之后的驱动
      if (data) {
        if (data.backSeq == 1 && !data.resultEnum) {
          //控制盒收到开锁命令
          that.data.openLockStat = true; //当前正在开锁
          connectShow.openLockingShow()
        } else if (data.backSeq == 2) { // mark: 开锁完成
          leaseShow.openLockOverTip()
          that.setData({
            openning_show: false
          })
          //开锁结束
          that.clear85Timer();
          BLELocker.stop85Back1Timeout();
          BLELocker.stop85Back2Timeout();

          that.data.openLockStat = false; //当前开锁结束
          if (data.noEject == 1) { //设备未弹出
            leaseShow.resultHide();
            let descMini = pile_id + '-' + ConstantData.err_type.data_85_back2_noeject_inner;
            statistic.noEjectDialog(that, descMini);
            that.recordBlueConnectError(ConstantData.err_type.data_85_back2_noeject_inner, '85第二条回执提示未弹出，显示“未弹出弹框”');
          } else {
            console.log("开锁后断开蓝牙--ccc->")
            app.globalData.isConnecting = false;
            BLELocker.disconnect('index3456')

            if (!that.data.equId || !that.data.opentime) {
              that.data.equId = wx.getStorageSync('equId');
              that.data.opentime = wx.getStorageSync('opentime');
            }
            this.data.isToTipBackSucPage = true
          }

        } else {
          leaseShow.openLockOverTip()
          console.log('UI层收到85数据', data)
          that.data.openLockStat = false; //当前开锁结束
          if (!that.data.equId || !that.data.opentime) {
            that.data.equId = wx.getStorageSync('equId');
            that.data.opentime = wx.getStorageSync('opentime');
          }
          this.data.isToTipBackSucPage = true
        }
      } else {
        that.data.openLockStat = false; //当前开锁结束
        if (that.data.hasOrderFlg && that.data.no_eject_flg || that.data.no_eject_back_flg == 1) {
          let descMini = pile_id + '-' + ConstantData.err_type.data_85_null_inner;
          statistic.noEjectDialog(that, descMini);
          that.recordBlueConnectError(ConstantData.err_type.data_85_null_inner, '85回执为空，显示“未弹出弹框”');
        } else {
          bleFailShow.modalMsgShow()
          //1.关闭租凭开锁提示对话框 2.提示用户开锁失败,请重新扫码
          that.setData({
            showModalStatus: false,
            loading_show: false,
            mapShowStatus: true,
            openning_show: false,
            openLockLeaseOptStatus: true,
            modal: {
              modal_show: true,
              desc: '开锁失败,扫码归还后重试',
              desc_mini: '85null' + pile_id + '-' + ConstantData.err_type.data_85_null_else,
              comfirm: true
            },
          })
          that.recordBlueConnectError(ConstantData.err_type.data_85_null_else, 'modalErr:85null');
          app.sendLog();
        }
      }

    } else if (status == BLELocker.Status.ble95Data) {
      wx.removeStorageSync('retryConCounts');
      app.globalData.conIsSuc = true;
      if (app.globalData.conTimeoutTimer) {
        clearTimeout(app.globalData.conTimeoutTimer);
      }
      if (app.globalData.data95ReceiveTimer) {
        clearTimeout(app.globalData.data95ReceiveTimer);
      }
      if (app.globalData.directConnectTimer) {
        clearTimeout(app.globalData.directConnectTimer);
      }
      if (app.globalData.auto95RecTimer) {
        clearTimeout(app.globalData.auto95RecTimer);
      }

      //设置全局的首页对象句柄，便于开锁85时进行调用
      console.warn('ble95Data---->', data);
      let conTimeLen = app.globalData.startConTime ? (new Date().getTime() - app.globalData.startConTime) : -1;
      let err95TypeVal = that.data.retry95Flg ? ConstantData.err_type.retry_send_95_log : ConstantData.err_type.receive_95_time;
      that.recordBlueConnectError(err95TypeVal, 'ble95Data:' + conTimeLen);
      //数据读取中
      if (that.data.curIsDirectCon && app.globalData.isDirectConnect) {
        that.recordBlueConnectError(40012, 'directConnect success');
      }
      let nowTime = new Date().getTime();

      //防止连续95数据 start
      if (that.data.data95Time && (nowTime - that.data.data95Time < that.data.many95DataInterval)) {
        console.log('操作频繁');
        that.data.data95Time = nowTime;
        that.recordBlueConnectError(ConstantData.err_type.data_95_repeat, '连续95数据,已忽略');
        return;
      }
      that.data.data95Time = nowTime;
      //防止连续95数据 end

      if (that.data.send85Time && (nowTime - that.data.send85Time < that.data.blue95Interval)) {
        console.log('操作频繁，忽略95数据');
        that.setData({
          loading_show: false
        })
        wx.showToast({
          title: '您的操作过于频繁，请稍候再试',
          icon: 'none'
        })
        return;
      }
      //数据已返回开始处理
      connectShow.handle95Data()
      if (data == null) {
        bleFailShow.modalMsgShow()
        //1.关闭正在连接的提示对话框 2.弹出提示用户连接设备失败,重新扫码
        that.setData({
          showModalStatus: false,
          mapShowStatus: true,
          loading_show: false,
          modal: {
            modal_show: true,
            desc_mini: '95null' + pile_id + '-' + ConstantData.err_type.data_95_null,
            desc: '连接失败,请扫码重试',
            confirm: true
          }
        })
        that.recordBlueConnectError(ConstantData.err_type.data_95_null, 'modalErr:95null');
        app.sendLog();
      } else {
        getApp().hideLoading()

        that.data.elecInt = data.electrict; //归位桩剩余电量
        console.log("处理95指令接收的数据", data)
        let location = wx.getStorageSync('location')
        data.location = location
        that.data.static95Data = data;
        console.log("处理95指令接收的数据2", data)
        let dataType = "95data";
        statistic.statisticData(dataType, JSON.stringify(that.data.static95Data));

        if (data.mac && that.data.conMac && data.mac != that.data.conMac) {
          BLELocker.disconnect('condev1611', 'stopConnect');
          that.recordBlueConnectError(ConstantData.err_type.data_95_no_lastest, '不是最新扫码95数据:' + data.mac + "," + that.data.conMac);
          return;
        }

        if (data.motorStat == 1) {
          bleFailShow.modalMsgShow()
          that.setData({
            showModalStatus: false,
            mapShowStatus: true,
            loading_show: false,
            openning_show: false,
            modal: {
              modal_show: true,
              desc: '设备重启中，请稍候再试',
              desc_mini: pile_id + '-' + ConstantData.err_type.data_95_motorunning,
              confirm: true
            }
          });
          that.recordBlueConnectError(ConstantData.err_type.data_95_motorunning, "95马达状态motorStat-" + data.motorStat + '-rfid-' + data.rfid);
          return;
        }

        if (that.data.canRetry85) {
          //如果是三分钟之内，显示未弹出弹框
          console.warn('--未弹出，重新连接成功，发送85');
          if (that.data.retryType85 == 'auto') {
            that.recordBlueConnectError(ConstantData.err_type.data_95_85_retry_atuo, '自动重试租借，重新连接成功，开始发送85');
          } else {
            that.recordBlueConnectError(ConstantData.err_type.data_95_85_retry, '用户点击重试租借，重新连接成功，开始发送85');
          }
          that.data.canRetry85 = false;
          that.send85Command();
          return;
        }

        if (that.data.pileLocation != undefined && that.data.pileLocation != null) {
          data.location = that.data.pileLocation;
        }
        let version = BLELocker.getDriverVersion();
        if (!data.pile_ver) {
          data.pile_ver = version;
        }

        let sysInfo = wx.getStorageSync("systeminfo");
        data.phoneType = sysInfo.model;
        var electrict = data.electrict; //归位桩剩余电量
        let noEject = data.chairIsEjectLose;
        let no_eject_times = 0;
        if (noEject == 1) {
          no_eject_times = wx.getStorageSync('no_eject_times') || 1;
          wx.setStorageSync('no_eject_times', no_eject_times + 1)
        } else {
          wx.removeStorageSync('no_eject_times')
        }
        let user_no_back = wx.getStorageSync('user_no_back')
        console.log('no_eject_times============', no_eject_times, user_no_back)
        if (no_eject_times > 2 && !user_no_back) {
          bleFailShow.modalMsgShow()
          that.setData({
            showModalStatus: false,
            mapShowStatus: true,
            loading_show: false,
            openning_show: false,
            modal: {
              modal_show: true,
              desc: '请换一台设备租赁',
              desc_mini: 'noEject' + pile_id + '-' + ConstantData.err_type.data_95_noeject,
              confirm: true
            }
          });
          that.recordBlueConnectError(ConstantData.err_type.data_95_noeject, "modalErr-mac=" + data.mac);
          return;
        }


        if (app.globalData.conBlueVer && app.globalData.conBlueVer == 'om-phy-1.0') {} else {
          //发送控制盒广播配置命令
          BLELocker.sendBroadcastConfCommand();
          if (that.data.isSend98Cmd) {
            setTimeout(function () {
              //发送98获取数据
              that.send98Command(version);
            }, 200);
          }
        }


        that.setData({
          hookStatus: data.hookStatus,
          switchStatus: data.chairSwitchSatus,
          didiStat: data.programRestartTimes,
          // picTip: picTipDesc,
          mac: data.mac,
          rfid: data.rfid,
          rfidIsCache: data.rfidIsCache ? data.rfidIsCache : -100
        })
        var mac = data.mac;
        console.log("mac=" + mac + ",left electrit -->" + electrict)
        var rfId = data.rfid;
        var costTime = data.costTime;
        //存储控制盒上报的记录的时长
        that.data.conBoxCostTime = data.costTime;
        console.log("rfId=" + rfId + ",costTime=" + costTime)



        that.data.blankPileOpenFlg = false;

        //空桩开锁权限判断,有空桩开锁权限且rfid不识别或rfid从缓存中读取的，可直接进行开锁
        let isBlankOpen = (data.rfidIsCache == 1 || 'FFFFFFFF' == rfId) && that.data.isNoRfidOpen == 1; //空桩开锁权限
        isBlankOpen = that.data.isNoRfidOpen == 2 || isBlankOpen; //存在辅助开锁权限的不做空桩判断可直接开锁20200805145400
        if (isBlankOpen) {
          wx.showLoading({
            title: '检测中..',
          });

          setTimeout(function () {
            getApp().hideLoading();
            if (that.data.isColonyCon) {
              colonyBlue.openLock(that.data.mac, that, 1);
            } else {
              that.data.blankPileOpenFlg = true;
              that.send85Command();
            }
            that.setData({
              loading_show: false,
              openning_show: false
            })
            wx.showToast({
              title: '开锁完成',
            })

          }, 2000);
        } else if ('FFFFFFFF' == rfId) { //轮椅未识别
          let rfid_error_time = wx.getStorageSync('rfid_error_time') || 1;
          wx.setStorageSync('rfid_error_time', rfid_error_time + 1);
          let errType = '';
          //第3次不识别
          if (rfid_error_time > 2) {
            bleFailShow.modalMsgShow()
            //判断是否归还
            if (user_no_back) {
              errType = ConstantData.err_type.data_95_rfid_back_times;
              that.setData({
                modal: {
                  desc: "请确认设备已经锁好且拉不下来后可联系客服帮您归还",
                  desc_mini: "rfid不识 " + pile_id + "-" + errType,
                  modal_show: true,
                  contact: true
                }
              })
            } else {
              errType = ConstantData.err_type.data_95_rfid_rent_times;
              let desc = that.data.connectType && that.data.connectType == '归还' ? '未识别到设备，请联系客服' : '请换一个设备租赁';
              that.setData({
                modal: {
                  desc: desc,
                  desc_mini: "rfid不识 " + pile_id + "-" + errType,
                  modal_show: true,
                  confirm: true,
                }
              })
            }
            BLELocker.disconnect('index4608', 'stopConnect');
          } else {
            bleFailShow.modalMsgShow()
            //判断是否归还
            if (user_no_back) {
              errType = ConstantData.err_type.data_95_rfid_back;
              let desc = '请将轮椅靠右摆放且听到滴滴两声后再点击重试。'
              if (that.data.pile_type) {
                desc = '请将轮椅摆正。然后往里推着轮椅，听到滴滴两声后再点击重试。'
              }
              that.setData({
                modal: {
                  desc: desc,
                  desc_mini: "rfid不识 " + pile_id + "-" + errType,
                  retry95: true,
                  img1_show: true,
                  modal_show: true,
                }
              })
            } else {
              if (data.chairSwitchSatus == 0) {
                errType = ConstantData.err_type.data_95_rfid_rent_noInsert;
                that.setData({
                  modal: {
                    modal_show: true,
                    desc: '当前桩上没有设备，请换一个有设备的桩租赁哦。',
                    desc_mini: "rfid不识 inSwitch " + pile_id + "-" + errType,
                    cancel: true,
                    reScan: true,
                  }
                })
                BLELocker.disconnect('index4628', 'stopConnect');
              } else {
                errType = ConstantData.err_type.data_95_rfid_rent;
                let desc = '请将轮椅左右摇晃并靠右摆放后点击重试'
                if (that.data.pile_type) {
                  desc = '请将轮椅摆正。然后往里推着轮椅点击重试。'
                }
                that.setData({
                  modal: {
                    desc: desc,
                    modal_show: true,
                    desc_mini: "rfid不识 " + pile_id + "-" + errType,
                    retry95: true,
                    img1_show: true,
                  }
                })
              }

            }
          }
          if (errType) {
            that.recordBlueConnectError(errType, "modalErr:rfid不识别");
          }
        } else if ('00000000' == rfId && data.chairSwitchSatus == 0) { //共享陪护床
          bleFailShow.modalMsgShow()
          if (user_no_back && wx.getStorageSync('user_no_back').data.noBack.lockType == '宜家锁') {
            that.setData({
              showyijia: true,
              modal: {
                desc: "请确认设备已按照图示锁好后\n点击重试。",
                desc_mini: "PHC inSwitch " + pile_id + "-" + ConstantData.err_type.data_95_phc,
                modal_show: true,
                contact: true,
              }
            })
          } else if (user_no_back && wx.getStorageSync('user_no_back').data.noBack.lockType != '宜家锁') {
            that.setData({
              modal: {
                desc: "请检查设备是否已经锁好\n如果已锁好，请联系客服帮您归还。",
                desc_mini: "PHC inSwitch " + pile_id + "-" + ConstantData.err_type.data_95_phc,
                modal_show: true,
                contact: true,
              }
            })
          } else { // mark: 陪护椅锁95开关错误
            if (that.data.showStat.openOverConfirm) {
              console.log("开锁完成，收到的95日志")
              return
            }
            that.setData({
              modal: {
                desc: "该设备故障，请更换一个设备使用！",
                desc_mini: "PHC inSwitch " + pile_id + "-" + ConstantData.err_type.data_95_phc,
                modal_show: true,
                confirm: true
              }
            })
          }
          that.recordBlueConnectError(ConstantData.err_type.data_95_phc, "modalErr:陪护床插入开关错误");
        } else if (that.data.isJudgeInsertSwitch && that.data.isNoRfidOpen != 1 && data.chairSwitchSatus == 0 && user_no_back && data.programRestartTimes != 1) { //isJudgeInsertSwitch:判断插入开关;isNoRfidOpen:空桩开锁;
          BLELocker.disconnect('index4630', 'stopConnect');
          that.recordBlueConnectError(10060, '用户中断连接4630');
          //用户归还且插入状态不对
          let insert_fail_time = wx.getStorageSync('insert_fail_time') || 1;
          wx.setStorageSync('insert_fail_time', insert_fail_time + 1);
          bleFailShow.modalMsgShow()
          let errType = '';
          //第3次
          if (insert_fail_time > 2) {
            errType = ConstantData.err_type.data_95_noInsert_times;
            that.setData({
              modal: {
                desc: "请确认设备已经锁好且拉不下来后可联系客服帮您归还。",
                desc_mini: "inSwitch " + pile_id + "-" + errType,
                modal_show: true,
                contact: true
              }
            })
          } else {
            errType = ConstantData.err_type.data_95_noInsert;

            that.setData({
              modal: {
                desc: "1、请检查设备是不是已经锁好\n2、如果已经锁住，请将轮椅摆正，然后往里推着轮椅点击重试。",
                desc_mini: "inSwitch " + pile_id + "-" + errType,
                modal_show: true,
                img2_show: true,
                retry95: true,
                desc_center: false,
              }
            })
          }

          if (errType) {
            that.recordBlueConnectError(errType, "modalErr:插入开关错误");
          }
        } else {
          wx.removeStorageSync('rfid_error_time');
          wx.removeStorageSync('insert_fail_time');

          if (that.data.canceledConnect) {
            that.recordBlueConnectError(10061, "用户中断连接1");
            return;
          }
          that.openOrReturnEquitment(rfId, mac, costTime); //开锁或归还
        }
      }
    } else if (status == BLELocker.Status.ble75zeroData) {
      //75第0包数据
      console.log("接收到格子柜第0包数据", data, app.globalData.data75ReceiveTimer);
      if (app.globalData.data75ReceiveTimer) {
        clearTimeout(app.globalData.data75ReceiveTimer);
      }
      if (app.globalData.conTimeoutTimer) {
        clearTimeout(app.globalData.conTimeoutTimer);
        app.globalData.conTimeoutTimer = null;
      }
      //发送获取各个门的状态信息
      if (data) {
        that.setData({
          openning_show: false,
          connectDesc: "数读设备成功,读取格子状态中...",
          loading_show: true,
          loading_desc: '读取格子状态中01...',
        });
        that.data.latticeCabinetData = new Object();
        that.data.latticeCabinetData.latticeData = data;
        that.data.latticeCabinetData.doorDataList = new Array();
        let equStatData = data.equStat;
        let doorCount = parseInt(equStatData.maxDoorCount, 16);
        console.log("格子柜的在线门数量---->", doorCount, equStatData.maxDoorCount);

        that.data.data75NReceiveTimer = setTimeout(function () {
          console.log("75N包数据接收超时...", callback);
          that.handleStatus(BLELocker.Status.bleRecive75NTimeout);
        }, 8000);

        that.send75Command("01");
        //  for(var i=1;i<=doorCount;i++) {
        //     let doorNum = i < 10 ? "0" + i : i;
        //     setTimeout(function(){
        //       that.send75Command(doorNum);
        //     },100);            
        //  }
      } else {
        wx.showModal({
          showCancel: false,
          title: '温馨提示',
          content: '获取柜信息失败,请扫码重试',
          success(res) {}
        })
      }

    } else if (status == BLELocker.Status.ble75NData) {
      //75第N包数据
      console.log("接收到格子柜第N包数据", data, that.data.latticeCabinetData, app.globalData.data75ReceiveTimer);

      if (data) {
        if (!that.data.latticeCabinetData) {
          that.data.latticeCabinetData = new Object();
        }
        if (!that.data.latticeCabinetData.doorDataList) {
          that.data.latticeCabinetData.doorDataList = new Array();
        }
        that.data.latticeCabinetData.doorDataList.push(data);
        let doorMaxCount = that.data.latticeCabinetData.latticeData ? parseInt(that.data.latticeCabinetData.latticeData.equStat.maxDoorCount, 16) : 0;
        let getDoorCount = that.data.latticeCabinetData.doorDataList.length;
        if (doorMaxCount == getDoorCount) {
          //已接收完门的总数量
          if (that.data.data75NReceiveTimer) {
            clearTimeout(that.data.data75NReceiveTimer);
          }

          //记录格子柜信息日志
          let mac = that.data.conMac;
          that.data.latticeCabinetData.mac = mac;
          statistic.statisticData("75data", JSON.stringify(that.data.latticeCabinetData));

          //开始请求是否可以开锁          
          let doorNumArr = new Array();
          let doorRfidArr = new Array();
          for (var i = 0; i < getDoorCount; i++) {
            let doorData = that.data.latticeCabinetData.doorDataList[i].doorStat;
            let doorNum = doorData.doorNum;
            let isOnline = doorData.doorStat;
            let rfid = doorData.rfid;
            let binStat = doorData.binStat;
            if (isOnline != 'FF') {
              let num = parseInt(doorNum, 16);
              doorNumArr.push(num);
              let doorRfidStr = num + ":" + rfid + ":" + binStat;
              doorRfidArr.push(doorRfidStr);
            }
          }
          let doorNumStr = doorNumArr.join(',');
          let doorRfidStr = doorRfidArr.join(',');
          that.setData({
            openning_show: false,
            connectDesc: "门状态读取成功,开始请求开锁信息...",
            loading_show: true,
            loading_desc: '请求开锁信息中...',
          });
          //进行开锁
          that.latticeOpen(mac, doorNumStr, doorRfidStr);
        } else {
          let doorNum = parseInt(data.doorStat.doorNum, 16) + 1;
          let doorNumHex = doorNum.toString(16);
          doorNumHex = doorNumHex.length == 1 ? "0" + doorNumHex : doorNumHex;
          that.setData({
            openning_show: false,
            connectDesc: "数读设备成功,读取格子状态中" + doorNumHex + "...",
            loading_show: true,
            loading_desc: '读取格子状态中' + doorNumHex + '...',
          });
          setTimeout(() => {
            that.send75Command(doorNumHex);
          }, 100);

        }
      } else {
        wx.showModal({
          showCancel: false,
          title: '温馨提示',
          content: '获取锁信息失败,请扫码重试',
          success(res) {}
        })
      }

    } else if (status == BLELocker.Status.ble98Data) {
      //98数据记录
      let dataType = "98data";
      console.log("------data>", data);
      data.push(that.data.mac);
      data.push(that.data.rfid);
      console.log("---98data,", data);

      statistic.statisticData(dataType, JSON.stringify(data));
    } else if (status == BLELocker.Status.bleRecive75Timeout) {
      //蓝牙75第0包接收超时
      wx.showModal({
        showCancel: false,
        title: '温馨提示',
        content: '获取设备信息超时,请扫码重试',
        success(res) {}
      })
    } else if (status == BLELocker.Status.bleRecive75NTimeout) {
      //蓝牙75第N包接收超时
      wx.showModal({
        showCancel: false,
        title: '温馨提示',
        content: '获取锁信息超时,请扫码重试',
        success(res) {}
      })
    } else if (status == BLELocker.Status.bleRecive76Timeout) {
      that.setData({
        loading_show: false,
      });
      //蓝牙75第N包接收超时
      wx.showModal({
        showCancel: false,
        title: '温馨提示',
        content: '开锁响应超时,如果未开门,请扫码重试',
        success(res) {}
      })
    } else if (status == BLELocker.Status.ble76Data) {
      if (app.globalData.data76ReceiveTimer) {
        clearTimeout(app.globalData.data76ReceiveTimer);
        app.globalData.data76ReceiveTimer = null;
      }
      //格子柜开锁结果返回数据
      console.log("格子柜开锁结果返回数据", data);
      that.setData({
        openning_show: false,
        loading_show: false,
      });
      wx.showModal({
        showCancel: false,
        title: '温馨提示',
        content: '门已打开成功，谢谢使用!',
        success(res) {}
      })
      app.globalData.isConnecting = false;
      BLELocker.disconnect('index5445');
      let mac = that.data.conMac;
      data.mac = mac;
      statistic.statisticData("76data", JSON.stringify(data));
    } else if (status == BLELocker.Status.bleOneMorePhyLockStatusData) {
      //one more 陪护椅锁状态信息
      console.log("one more 陪护椅锁状态信息 处理-->", data);
      if (data.hookStatus == 1) {
        //锁舌未弹出,发送锁舌弹出命令后再查询收费规则
        BLELocker.oneMorePhyBleLock();
        setTimeout(() => {
          that.handleStatus(BLELocker.Status.ble95Data, data);
        }, 100);
      } else {
        //相当于95命令，进行收费规则请求然后，点击开锁进行开锁
        that.handleStatus(BLELocker.Status.ble95Data, data);
      }
    } else if (status == BLELocker.Status.bleReciveOneMorePhyTokenTimeout) {
      that.setData({
        loading_show: false,
      });
      //接收one more的陪护椅token超时   
      wx.showModal({
        showCancel: false,
        title: '温馨提示',
        content: '设备token响应超时,请扫码重试',
        success(res) {}
      })
    } else if (status == BLELocker.Status.bleSendOneMorePhyUnlockTimeout) {
      //one more 陪护椅开锁超时
      that.setData({
        loading_show: false,
        openning_show: false,
      });
      //接收one more的陪护椅token超时   
      wx.showModal({
        showCancel: false,
        title: '温馨提示',
        content: '开锁超时,请扫码重试',
        success(res) {}
      })
    } else if (status == BLELocker.Status.bleOneMorePhyUnLockData) {
      //one more 陪护椅开锁结果
      console.log("one more 陪护椅开锁结果：", data);
      that.handleStatus(BLELocker.Status.ble88Data, data);
    } else if (status == BLELocker.Status.bleSend95DevNull || status == BLELocker.Status.bleSend95ConDis) {
      //发送95指令时设备信息为空或蓝牙断开连接
      that.setData({
        loading_show: false,
      });
      app.globalData.isConnecting = false;
      BLELocker.disconnect('index5430');
      that.recordBlueConnectError(ConstantData.err_type.data_95_send_fail, "发送95失败status=" + status);

      //接收one more的陪护椅token超时   
      wx.showModal({
        showCancel: false,
        title: '温馨提示',
        content: '获取设备数据失败,请扫码重试',
        success(res) {}
      })

      clearTimeout(app.globalData.data95ReceiveTimer);
      clearTimeout(app.globalData.auto95RecTimer);
    }

  },

  clickBeeBanner() {
    wx.navigateToMiniProgram({
      appId: this.data.beeBannerConfig.appId,
      path: this.data.beeBannerConfig.path,
      success(res) {
        console.log('【小蜜蜂广告跳转】跳转成功：' + JSON.stringify(res))
        util.bee_record_user_action(ConstantData.CONSTATNT_DATA.BASE_URL, -30002, '租借成功-小蜜蜂底部广告', 'success')
      },
      fail(error) {
        console.log('【小蜜蜂广告跳转】跳转失败：' + JSON.stringify(error))
        util.bee_record_user_action(ConstantData.CONSTATNT_DATA.BASE_URL, -30002, '租借成功-小蜜蜂底部广告', 'fail')
      }
    })
  },

  toViewNoDepositProtocol: function () {
    this.data.isToViewProtocol = true
    wx.navigateTo({
      url: '../../../pkgBak/pages/help/protocol/wx_no_deposit/wx_no_deposit',
    })
  },

  toViewLeaseProtocol: function () {
    this.data.isToViewProtocol = true
    wx.navigateTo({
      url: '../../../pkgBak/pages/help/lease/lease',
    })
  },

  /**
   * 等待接收蓝牙消息,进行开锁或归还操作
   * @param eqId
   * @param hid
   * @param costTime
   */
  openOrReturnEquitment: function (rfId, mac, costTime) {
    var that = this
    //服务端接口存在没有上传的数据为空
    if (!rfId) {
      //将接收到95数据的赋值
      rfId = that.data.rfid;
    }
    if (!mac) {
      //将扫码时获取的mac赋值
      mac = that.data.conMac;
    }
    if (!costTime) {
      //将接收到95数据时的赋值
      costTime = that.data.conBoxCostTime;
    }

    this.setData({
      rfId: rfId,
      modal: {
        modal_show: false,
        title: '温馨提示'
      }
    })

    //请稍等,处理数据中...
    connectShow.getRuleOrBack()
    that.data.openLockGetData = null
    that.data.reqOpenLockTime = null
    that.data.openTime = null
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/open_lock',
        method: 'post',
        header: header,
        data: {
          depositAutoBack: that.data.depositAutoBack,
          rfId: rfId,
          mac: mac,
          costTime: costTime,
          refund: that.data.refund,
          hookStatus: that.data.hookStatus,
          switchStatus: that.data.switchStatus,
          didiStat: that.data.didiStat,
          rfidIsCache: that.data.rfidIsCache,
          isScanBack: that.data.isScanBack,
        },
        success: function (res) {
          // 模拟测试 res.data.rulePic = 'https://img2.baidu.com/it/u=3717708487,1315811776&fm=253&fmt=auto&app=138&f=JPEG?w=1280&h=365'
          let isBeforeLeaseTip = true
          that.data.openLockGetData = res
          that.data.conMac = mac
          //校验服务器
          if(!that.data.reqOpenLockTime) {
            that.data.reqOpenLockTime = new Date().getTime()
          }else {
            let diff = new Date().getTime() - that.data.reqOpenLockTime
            if(diff < 5000) {
               wx.showToast({
                  title: '处理中..',
               })
               return
            }
          }
          
          that.handleOpenLockData(isBeforeLeaseTip)
        },
        fail: function (res) { // mark: 请求open_lock接口失败
          wx.showToast({
            title: '网络异常请重试',
          })
          leaseShow.netFail("网络异常，请重新扫码租借")
        },
        complete: function (res) {
          if (that.data.canceledConnect) {
            that.recordBlueConnectError(10062, "用户中断连接2");
            return;
          }
          that.setData({
            loading_show: false
          })

          setTimeout(function () {
            that.recordBlueConnectError(ConstantData.err_type.open_lock_res, "开始请求是否符合开锁租赁条件" + rfId + ' 请求结果:' + (res.data ? res.data.rst : '空'));
          }, 300);

        }
      })

    })

  },
  // mark: 处理开锁数据信息
  handleOpenLockData: function (isBeforeLeaseTip) {
    let that = this
    let mac = that.data.conMac
    let res = that.data.openLockGetData
    console.warn("开锁访问服务返回结果===========res=", res)

    common.clearConTimeCountTimer('112');

    let pile_id = that.data.pile_id ? 'Z' + that.data.pile_id : '';
    let errType = '';
    let netErr = app.handleRes(res, that);
    if (netErr) {
      return
    }
    if (that.data.canceledConnect) {
      that.recordBlueConnectError(10062, "用户中断连接2");
      return;
    }
    //记录校验结果日志
    setTimeout(function () {
      that.recordBlueConnectError(ConstantData.err_type.open_lock_suc, "返回校验结果:" + JSON.stringify(res.data));
    }, 1000);

    var data = res.data
    that.data.leftFreeTimeTipContent = data.leftFreeTimeTipStr
    that.data.no_eject_flg = data.no_eject;
    if (data.backSucVoiceUrl) {
      that.data.voiceTempFilePath = data.backSucVoiceUrl;
    }
    //未准确插入归位桩
    if (data.rst == -133) {
      //记录未准确插入桩的时间
      errType = ConstantData.err_type.open_lock_133;
      that.recordReturnBlueTimeoutError(2, '');
      app.globalData.isConnecting = false;
      BLELocker.disconnect('index2022');

      var nophone = app.getUserLoginNoPhone();
      if (nophone == null || nophone == undefined || nophone == 1) {
        wx.setStorageSync("alertBoxTipContent", data.errInfo);
        that.setData({
          phoneAuthStatus: true,
          phoneAuthBtt: 'no_return_blue_timeout',
          loading_show: false
        });
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        })
        return;
      }

      leaseShow.resultShow(data.errInfo + errType)

      return
    }

    if (data.rst == 12) { //帮代租设备已成功归还 // mark: 帮代租设备已成功归还
      app.globalData.isConnecting = false;
      BLELocker.disconnect('index2043')
      leaseShow.resultShow('帮代租设备已成功归还')
      return
    }

    if (data.rst == '-138') { //帮代租设备已成功归还
      app.globalData.isConnecting = false;
      BLELocker.disconnect('index2676')
      that.setData({
        showDialog: true,
        alertBoxTipContent: data.eqId,
        // msgRst: 6,
        alertBoxBtnName: '重新扫码',
        wxDeviceId: data.deviceId,
        wxConnType: data.connType
      })
      return
    }

    if (data.rst == 13) {
      errType = ConstantData.err_type.open_lock_13;
      app.globalData.isConnecting = false;
      BLELocker.disconnect('index2280')
      bleFailShow.modalMsgShow()
      that.setData({
        modal: {
          modal_show: true,
          desc: data.errInfo ? data.errInfo : '当前时间不可租借' + errType,
          confirm: true
        }
      })
      return;
    }
    if (data.rst == 14) {
      errType = ConstantData.err_type.open_lock_14;
      bleFailShow.modalMsgShow()
      that.setData({
        modal: {
          modal_show: true,
          desc: data.errInfo ? data.errInfo : '您的操作过于频繁，请稍候再试' + errType,
          confirm: true
        }
      })
      return;
    }
    console.log('elecInt---------homeMinLeftElectricity', that.data.elecInt, data.homeMinLeftElectricity)
    if (that.data.elecInt < data.homeMinLeftElectricity) { // mark: 正安排更换电池
      errType = ConstantData.err_type.open_lock_15;
      app.globalData.isConnecting = false;
      BLELocker.disconnect('index2056')
      leaseShow.resultShow('正安排更换电池,请租赁其他设备' + pile_id + '-' + errType)
      that.recordBlueConnectError(errType, "开锁:正安排更换电池,请租赁其他设备,mac=" + mac)

      return;
    }

    //判断是否存在绑定的账号，存在则弹出选择的列表 // mark: 是否存在帮代借账号
    var bindUserList = data.bindUserInfoList
    var agentEmployerList = data.agentEmployerList
    if (agentEmployerList && agentEmployerList.length > 0) {
      var sureLeaseTipInfo = '请提醒用户及时归还'
      //门诊爱心租赁列表
      that.setData({
        bindUserType: 2,
        bindUserListStatus: true,
        mapShowStatus: false,
        showModalStatus: false,
        agentLeaseSelStatus: false,
        bindUserList: agentEmployerList,
        wxDeviceId: data.deviceId,
        wxConnType: data.connType,
        wxEqId: data.eqId,
        wxHid: data.hid,
        wxEqTid: data.eqTid,
        leftTimeLenStr: sureLeaseTipInfo
      })
      return
    }

    if (bindUserList && bindUserList.length > 0) {
      //包时卡绑定用户
      that.setData({
        bindUserType: 1,
        bindUserListStatus: true,
        mapShowStatus: false,
        showModalStatus: false,
        agentLeaseSelStatus: false,
        bindUserList: bindUserList,
        wxDeviceId: data.deviceId,
        wxConnType: data.connType,
        wxEqId: data.eqId,
        wxHid: data.hid,
        wxEqTid: data.eqTid
      })
      return
    }

    var leaseSatus = data.closeDoorTip ? false : true;
    var systemInfo = wx.getStorageSync('systeminfo');
    var isCouldNoDeposit = util.isCouldNoDeposit(systemInfo);
    var isAllowNoDeposit = isCouldNoDeposit && data.wxNoDeposit == 1;
    console.log("-----isAllowNoDeposit=", isAllowNoDeposit);
    that.setData({
      isAllowNoDeposit: isAllowNoDeposit
    })

    let equTipInfo = data.equTipInfo;
    if (equTipInfo) {
      that.setData({
        //提示的图片列表
        imgUrls: equTipInfo.tipImgList,
        //是否显示轮播图的点
        indicatorDots: equTipInfo.tipImgList.lenght > 1,
        //提示的标题
        tipTitle: equTipInfo.title,
        //提示描述说明信息
        tipList: equTipInfo.tipList,
      })
    }

    if (data.rst == 0) {
      //已支付押金
      console.log("paied deposit getOpenLockData----", data)
      if (data.isSilenceBack == 1) {
        that.setData({
          isReturn: that.data.isReturn + 1
        })
      } else {
        that.setData({
          isReturn: 0
        })
        wx.removeStorageSync('no_eject_times')
      }

      var chargeRuleInfo = data.chargeRuleInfo
      wx.setStorageSync("no_pay_deposit", 0);
      if (isBeforeLeaseTip && that.data.isReturn == 0 && data.closeDoorTip) {
        // mark: 关门提前提醒
        let continueLeaseBtnLeft = false
        let contintueLeaseBtnName = '确定'
        let cancelBtnName = '取消'
        let tipContent = data.closeDoorTip
        leaseShow.beforeLeaseTipShow(continueLeaseBtnLeft, contintueLeaseBtnName, cancelBtnName, tipContent)
        return
      }
      data.deposit=data.deposit?.toString()?.split('.')
      that.setData({
        //设备押金                            
        equDeposit: data.deposit,
        bindUserType: 0,
        isPayDeposit: true,
        openLockLeaseOptStatus: true,
        rulePic: data.rulePic && data.rulePic.length > 0 ? data.rulePic : null,
        chargeRuleTitle: data.chargeRuleTitle,
        equTypeName: data.tName,
        chargeContent: chargeRuleInfo,
        showModalStatus: leaseSatus,
        hospitalTipBox: !leaseSatus,
        closeTipInfo: data.closeDoorTip,
        mapShowStatus: false,
        bindUserListStatus: false,
        agentLeaseSelStatus: false,
        bindUserList: [],
        wxDeviceId: data.deviceId,
        wxConnType: data.connType,
        wxEqId: data.eqId,
        wxHid: data.hid,
        wxEqTid: data.eqTid,
        serviceUuid: data.homing_uuid,
        homingFEC7: data.homing_FEC7,
        homingFEC8: data.homing_FEC8,
        homingFEC9: data.homing_FEC9,
        ruleList: data.ruleList,
        ruleDesc: data.ruleDesc,
        leaseMaxPriceStr: data.leaseMaxFeeStr,
        loading_show: false,
      })

      if(that.data.bleDepositPaySuc) {
        //标记押金支付成功后由于蓝牙断开重新连接
        that.data.read = true;
        that.openLock();
        return;
      }

      //显示收费规则
      leaseShow.chargeRuleShow()

      if (that.data.isReturn) {
        console.log("--remove-rst0-noback")
        wx.removeStorageSync('user_no_back');
        that.setData({
          connectType: '租借'
        })
        // 一分钟租借次数
        if (that.data.isReturn > 2) {

          bleFailShow.modalMsgShow()
          that.setData({
            modal: {
              desc: "设备" + pile_id + "网络异常，请换一台租赁",
              desc_mini: "一分钟-" + ConstantData.err_type.open_lock_one_min,
              modal_show: true,
              confirm: true,
            },
            showModalStatus: false
          })
          that.recordBlueConnectError(ConstantData.err_type.open_lock_one_min, 'modalErr:连续3次一分钟租借');
        }
      }


      BLELocker.setHomingDeviceServiceInfo(data.homing_uuid, data.homing_FEC7, data.homing_FEC8, data.homing_FEC9)

    } else {
      console.log("openLock statRst=" + data.rst)
      if (data.rst == 11) { //租赁记录支付完成        
        //归还数据信息
        that.data.backDataInfo = data

        leaseShow.backSucShow()
        app.globalData.isConnecting = false;
        BLELocker.disconnect('index2179')
        that.setData({
          msgRst: 1,
          alertBoxBtnName: '确  定',
          wxDeviceId: data.deviceId,
          wxConnType: data.connType,
          refundTip: that.data.refund, //1在租赁页面弹toast提示
          refund: 0,
          isBackChairStatus: false,
          refundEqTid: data.eqTid
        })

        that.data.isToTipBackSucPage = true

      } else if (data.rst == 1) { //归还设备,跳转到租金列表进行支付
        app.globalData.isConnecting = false;
        BLELocker.disconnect('index2198')
        that.setData({
          msgRst: 1,
          isBackChairStatus: false,
          alertBoxBtnName: '确  定',
          wxDeviceId: data.deviceId,
          wxConnType: data.connType
        })
        let rentInfo = {};
        rentInfo.backTime = data.backTime;
        rentInfo.borrowTime = data.openTime;
        rentInfo.costTime = data.timeLenStr;
        rentInfo.deposit = data.deposit;
        rentInfo.orderCode = data.orderCode;
        rentInfo.rent = data.rent;
        rentInfo.noPayTitle = data.noPayTitle;
        rentInfo.priceLabel = data.priceLabel;
        rentInfo.orderType = data.orderType;
        rentInfo.inCycleLeaseTimeLen = data.inCycleLeaseTimeLen || '';
        rentInfo.inCycleRecordInfoList = data.inCycleRecordInfoList || [];
        rentInfo.noPayDepositTip = data.noPayDepositTip;
        rentInfo.depositBackSuc = data.isAutoRefund;
        rentInfo.backSucVoiceUrl = data.backSucVoiceUrl;
        wx.navigateTo({
          url: '../../../pages/index/no_pay_tip/no_pay_tip?rentInfo=' + JSON.stringify(rentInfo)
        })

      } else if (data.rst == 2) { //同类设备只准租一个,提示用户归还的时候也需要扫一下二维码
        errType = ConstantData.err_type.open_lock_2;
        app.globalData.isConnecting = false;
        BLELocker.disconnect('index2214')
        if (data.leaseNoBackInfo) {
          //未归还的
          if (that.data.pt == 'noback' || (data.eqId && data.eqId != data.leaseNoBackInfo.equId)) {
            bleFailShow.modalMsgShow()
            that.setData({
              modal: {
                modal_show: true,
                desc_mini: errType,
                desc: "您有一台设备正在租借中！我们不支持同时租2个以上设备哦，请将前一台设备归还可继续租借。", // + data.leaseNoBackInfo.equId + "，这个L" + data.leaseNoBackInfo.equId + "轮椅锁在哪个桩位上，就扫哪个桩位玻璃面板上大的二维码就可以归还成功了",
                confirm: true,
                desc_center: true
              }
            })
          } else {
            console.log("跳转到未归还页面--------------------------------》")
            wx.navigateTo({
              url: '../../../pages/index/no_back_tip/no_back_tip?equId=' + data.leaseNoBackInfo.equId + "&positions=" + data.leaseNoBackInfo.positions + "&hospitalName=" + data.leaseNoBackInfo.hospitalName,
            })
          }
        } else {
          leaseShow.resultShow('很抱歉,您有未归还的' + data.tName) // mark: 很抱歉,您有未归还的设备
        }
      } else if (data.rst == 4 || data.rst == 5) { //同类设备只准租一个,提示用户归还的时候也需要扫一下二维码
        app.globalData.isConnecting = false;
        BLELocker.disconnect('index2242')
        that.setData({
          msgRst: 4,
        })
        console.log('data------------------------------------>', data)
        let rentInfo = {};
        rentInfo.backTime = data.backTime;
        rentInfo.borrowTime = data.openTime;
        rentInfo.costTime = data.timeLenStr;
        rentInfo.deposit = data.deposit;
        rentInfo.orderCode = data.orderCode;
        rentInfo.rent = data.rent;
        rentInfo.noPayTitle = data.noPayTitle;
        rentInfo.priceLabel = data.priceLabel;
        rentInfo.orderType = data.orderType;
        rentInfo.inCycleLeaseTimeLen = data.inCycleLeaseTimeLen || '';
        rentInfo.inCycleRecordInfoList = data.inCycleRecordInfoList || [];
        rentInfo.depositBackSuc = data.isAutoRefund;
        wx.navigateTo({
          url: '../../../pages/index/no_pay_tip/no_pay_tip?rentInfo=' + JSON.stringify(rentInfo)
        }) //0718mark--跳转到支付租金页面
      } else if (data.rst == 3) { //未交押金 // mark: 未交押金，可以帮代借
        wx.setStorageSync("no_pay_deposit", 1);
        //未交押金
        leaseShow.chargeRuleShow()
        data.deposit=data.deposit?.toString()?.split('.')
        that.setData({
          //设备押金
          equDeposit: data.deposit,
          callServiceTipContent: data.tName + "租赁需缴纳押金  ￥" + data.deposit,
          equId: data.eqId,
          toPayDeposit: !isAllowNoDeposit,
          isPayDeposit: false,

          bindUserType: 0,
          openLockLeaseOptStatus: true,
          rulePic: data.rulePic && data.rulePic.length > 0 ? data.rulePic : null,
          chargeRuleTitle: data.chargeRuleTitle,
          equTypeName: data.tName,
          chargeContent: data.chargeRuleInfo,
          showModalStatus: leaseSatus,
          hospitalTipBox: !leaseSatus,
          closeTipInfo: data.closeDoorTip,
          mapShowStatus: false,
          bindUserListStatus: false,
          agentLeaseSelStatus: false,
          bindUserList: [],
          wxDeviceId: data.deviceId,
          wxConnType: data.connType,
          wxEqId: data.eqId,
          wxHid: data.hid,
          wxEqTid: data.eqTid,
          serviceUuid: data.homing_uuid,
          homingFEC7: data.homing_FEC7,
          homingFEC8: data.homing_FEC8,
          homingFEC9: data.homing_FEC9,
          ruleList: data.ruleList,
          ruleDesc: data.ruleDesc,
          leaseMaxPriceStr: data.leaseMaxFeeStr,
          isReturn: data.isSilenceBack == 1
        })
        console.log('88888888888888')
        if (!that.data.isReturn) {
          wx.removeStorageSync('no_eject_times')
        }
        console.log('that.data.isPayDeposit--->>', that.data.isPayDeposit)
      } else if (data.rst == -102) {
        errType = ConstantData.err_type.open_lock_102;
        app.globalData.isConnecting = false;
        BLELocker.disconnect('index2289')
        var desc = data.errInfo ? data.errInfo : "设备维护中,请换其它桩租赁";
        if (desc == '已经关门,请在营业时间使用') {

        }
        bleFailShow.modalMsgShow()
        that.setData({
          modal: {
            modal_show: true,
            desc_mini: "L" + data.eqId + "维护中" + errType,
            desc: desc,
            confirm: true,
            desc_center: true
          }
        })

        that.recordBlueConnectError(errType, "开锁:设备维护中,请扫描其他设备,-102")

      } else if (data.rst == -104) {
        errType = ConstantData.err_type.open_lock_104;
        app.globalData.isConnecting = false;
        BLELocker.disconnect('index2300')
        bleFailShow.modalMsgShow()

        that.setData({
          modal: {
            modal_show: true,
            desc: "很抱歉,非法设备(" + (rfId ? rfId : '') + ")无法处理" + errType,
            confirm: true,
            desc_center: true
          }
        })

        that.recordBlueConnectError(errType, "开锁:很抱歉,非法设备无法处理,-104")

      } else if (data.rst == -137) {
        let user_no_back = wx.getStorageSync('user_no_back');
        let errType = '';
        if (user_no_back) {
          if (that.data.switchStatus == 0) {
            let insert_fail_time = wx.getStorageSync('insert_fail_time') || 1
            wx.setStorageSync('insert_fail_time', insert_fail_time + 1)
            if (that.data.no_eject_back_flg == 2) {
              insert_fail_time = 5;
            }

            bleFailShow.modalMsgShow()
            //第3次
            if (insert_fail_time > 2) {
              errType = ConstantData.err_type.open_lock_137_insert_back_times;
              that.setData({
                modal: {
                  desc: "请确认设备已经锁好且拉不下来后可联系客服帮您归还。",
                  desc_mini: "inSwitch " + pile_id + "-" + errType,
                  modal_show: true,
                  contact: true
                }
              })
            } else {
              errType = ConstantData.err_type.open_lock_137_insert_back;
              that.setData({
                modal: {
                  desc: "1、请检查设备是不是已经锁好。\n2、如果已经锁住，请将轮椅摆正，然后往里推着轮椅点击重试。",
                  desc_mini: "inSwitch " + pile_id + "-" + errType,
                  desc_center: false,
                  modal_show: true,
                  img2_show: true,
                  retry95: true,
                }
              })
            }

          } else if (that.data.hookStatus == 1) {
            //轮椅未锁好
            // if(that.data.lockType){
            //   that.setData({
            //     show_lockType:true
            //   })
            // }
            that.data.no_eject_back_flg = data.no_eject_back_flg ? data.no_eject_back_flg : '';
            if (that.data.no_eject_back_flg == 1) {
              //如果是同一用户同一桩位同一轮椅，且三分钟之内，则显示未弹出弹框，给用户再发一次85的机会
              errType = ConstantData.err_type.open_lock_137_hook_noeject_inner;
              console.warn('--三分钟之内，显示未弹出弹框');
              bleFailShow.openFailTipShow(errType)
              that.recordBlueConnectError(errType, '锁钩开关故障归还失败，三分钟之内，显示“未弹出弹框”');
              return;
            } else if (that.data.no_eject_back_flg == 2) {
              //如果是同一用户同一桩位同一轮椅，且三分钟之后，则直接提示联系客服进行归还
              errType = ConstantData.err_type.open_lock_137_hook_noeject_out;
              console.warn('--三分钟之后，提示联系客服');

              bleFailShow.modalMsgShow()

              that.setData({
                openning_show: false,
                loading_show: false,
                modal: {
                  modal_show: true,
                  desc: "请确认设备已经锁好且拉不下来后可联系客服帮您归还",
                  desc_mini: "hookSwitch " + pile_id + "-" + errType,
                  contact: true
                },
              })
              that.recordBlueConnectError(errType, '锁钩开关故障归还失败，三分钟之后，显示“联系客服归还”');
              return;
            }

            let hook_fail_time = wx.getStorageSync('hook_fail_time') || 1
            wx.setStorageSync('hook_fail_time', hook_fail_time + 1)

            bleFailShow.modalMsgShow()

            if (hook_fail_time > 2) {
              //第3次
              errType = ConstantData.err_type.open_lock_137_hook_back_times;

              that.setData({
                modal: {
                  modal_show: true,
                  desc: "请确认设备已经锁好且拉不下来后可联系客服帮您归还",
                  desc_mini: "hookSwitch " + pile_id + "-" + errType,
                  contact: true,
                }
              })
            } else {
              errType = ConstantData.err_type.open_lock_137_hook_back;

              that.setData({
                modal: {
                  desc: "请将轮椅摆正，将轮椅往里推一推，再左右摇晃轮椅。完成上述操作后点击重试。",
                  desc_mini: "hookSwitch " + pile_id + "-" + errType,
                  modal_show: true,
                  img3_show: true,
                  retry95: true,
                }
              })
            }

          } else {
            errType = ConstantData.err_type.open_lock_137_else;
            bleFailShow.modalMsgShow()
            that.setData({
              modal: {
                modal_show: true,
                desc: data.errInfo ? data.errInfo : '归还失败',
                desc_mini: pile_id + '-' + errType,
                desc_center: false,
                confirm: true,
              }
            })
            wx.removeStorageSync('insert_fail_time')
            wx.removeStorageSync('hook_fail_time')
          }
        } else {
          if (that.data.switchStatus == 0) {
            // if(that.data.lockType){
            //   that.setData({
            //     show_lockType:true
            //   })
            // }
            let insert_fail_time = wx.getStorageSync('insert_fail_time') || 1
            wx.setStorageSync('insert_fail_time', insert_fail_time + 1)
            bleFailShow.modalMsgShow()
            //第3次
            if (insert_fail_time > 2) {
              errType = ConstantData.err_type.open_lock_137_insert_rent_times;
              let desc = that.data.connectType && that.data.connectType == '归还' ? '请换一个设备归还，如果取不出来，请联系客服' : '请换一个设备租赁';
              that.setData({
                modal: {
                  desc: desc,
                  desc_mini: "inSwitch " + pile_id + "-" + errType,
                  modal_show: true,
                  contact: true,
                }
              })
            } else {
              errType = ConstantData.err_type.open_lock_137_insert_rent;

              that.setData({
                modal: {
                  desc: "1、请检查设备是不是已经锁好。\n2、如果已经锁住，请将轮椅摆正，然后往里推着轮椅点击重试。",
                  desc_mini: "inSwitch " + pile_id + "-" + errType,
                  desc_center: false,
                  modal_show: true,
                  img2_show: true,
                  retry95: true,
                }
              })
            }


          } else if (that.data.hookStatus == 1) {
            //轮椅未锁好
            let hook_fail_time = wx.getStorageSync('hook_fail_time') || 1
            wx.setStorageSync('hook_fail_time', hook_fail_time + 1)
            if (that.data.no_eject_back_flg == 2) {
              hook_fail_time = 5;
            }
            bleFailShow.modalMsgShow()
            if (hook_fail_time > 2) {
              //第3次
              errType = ConstantData.err_type.open_lock_137_hook_rent_times;
              let desc = that.data.connectType && that.data.connectType == '归还' ? '请换一个桩归还，如果取不出来，请联系客服' : '请换一个设备租赁';
              that.setData({
                modal: {
                  modal_show: true,
                  desc: desc,
                  desc_mini: "hookSwitch " + pile_id + "-" + errType,
                  contact: true
                }
              })
            } else {
              errType = ConstantData.err_type.open_lock_137_hook_rent;
              that.setData({
                modal: {
                  desc: "请将轮椅摆正，将轮椅往里推一推，再左右摇晃轮椅。完成上述操作后点击重试。",
                  desc_mini: "hookSwitch " + pile_id + "-" + errType,
                  modal_show: true,
                  img3_show: true,
                  retry95: true,
                }
              })
            }
          } else {
            errType = ConstantData.err_type.open_lock_137_else_rent;
            bleFailShow.modalMsgShow()

            that.setData({
              modal: {
                modal_show: true,
                desc: data.errInfo ? data.errInfo : '租借失败',
                desc_mini: pile_id + '-' + errType,
                desc_center: false,
                confirm: true,
              }
            })
            wx.removeStorageSync('insert_fail_time')
            wx.removeStorageSync('hook_fail_time')
          }
        }
        that.recordBlueConnectError(errType, "开锁:" + that.data.isBackChairStatus + "," + data.rst)
      } else if (data.rst == 20) {
        //归还成功后断开蓝牙 // mark: 帮扫码归还处理提示
        app.globalData.isConnecting = false;
        BLELocker.disconnect('index2564');
        //代归还成功            
        leaseShow.helpBackSucShow()
        that.recordBlueConnectError(ConstantData.err_type.open_lock_help_back, desc);

      } else if (data.rst == 21) {
        //点击归还扫码按钮,未绑定手机号
        wx.showModal({
          title: '温馨提示',
          content: '未绑定手机号,请先登录',
          success(res) {
            if (res.confirm) {
              //去登录页面
              wx.navigateTo({
                url: '../../../pages/login/login',
              })
            } else if (res.cancel) {
              console.log('用户点击取消')
            }
          }
        })



      } else {
        errType = ConstantData.err_type.open_lock_else;
        app.globalData.isConnecting = false;
        BLELocker.disconnect('index2366');
        var desc = data.errInfo ? data.errInfo : "请扫码重试";
        leaseShow.resultShow(desc + errType)
        that.recordBlueConnectError(errType, "开锁:" + desc + "," + data.rst)
      }
    }
  },

  //开锁
  openLock: function (e) { // mark: 免押租借/交押金租借
    var that = this
    that.data.bleDepositPaySuc = false;

    if (that.data.curContIsBle) {
      //判断蓝牙是否连接
      if (!app.globalData.devConnected) {
        leaseShow.resultShow("设备连接已断开，请重新扫码租借!")
        return
      }
    }
    if (!that.data.read) {
      wx.showToast({
        title: '请勾选我已阅读'
      })
      return
    }
    if (this.data.isAllowNoDeposit && !this.data.noDepositFail) {
      //允许免押
    } else if (!this.data.isPayDeposit) {
      //非免押且未支付押金,弹去支付押金的框
      //交押金租赁
      leaseShow.chargeRuleShow()      
      return;
    }

    if (that.data.openLockLeaseOptStatus == false) {
      console.log("租赁中")
      return
    }
    that.setData({
      openning_show: true,
      openning_desc: '开始请求租赁...',
      showModalStatus: false,
      mapShowStatus: true,
      loading_show: false,
      openLockLeaseOptStatus: false,
      bindUserListStatus: false,
      payDepositStat: false
    })

    that.recordBlueConnectError(ConstantData.err_type.deposit_create_order, "用户点击租赁,开始请求租赁-" + that.data.rfId)

    //进行租赁
    that.leaseEquipment();

  },

  //开锁并租赁设备
  leaseEquipment: function (isRedirectOpenLock) {

    var that = this
    console.log("代租赁-----uid=" + that.data.selBindUserId)

    var systemInfo = wx.getStorageSync('systeminfo');
    console.log("----->systeInfo=", systemInfo);
    var isCouldNoDeposit = util.isCouldNoDeposit(systemInfo);
    console.log("----->isCouldNoDeposit=", isCouldNoDeposit, that.data.isAllowNoDeposit);
     
    app.executeRequest(function (header) {
      console.log('header', header);
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/equipment_order',
        method: 'post',
        header: header,
        data: {
          eqid: that.data.wxEqId,
          hid: that.data.wxHid,
          eqtid: that.data.wxEqTid,
          bindUid: that.data.selBindUserId,
          bindUserType: that.data.bindUserType,
          isOldReq: 'lease_order', //2019-07-23用于兼容之前版本订单不能进行隐藏
          miniNoDeposit: isCouldNoDeposit && that.data.isAllowNoDeposit && !that.data.noDepositFail, //系统支持免押并且可以用户可以免押并且用户没有取消免押
          isGateway: that.data.isColonyCon //是否为网关下单,true是，false否
        },
        success: function (res) {
          let netErr = app.handleRes(res, that);
          if (netErr) {
            that.setData({
              openning_show: false,
            })
            return
          }
          that.data.send85Time = new Date().getTime();
          console.log('---租赁请求成功:', res)
          that.recordBlueConnectError(ConstantData.err_type.deposit_created_order, "生成记录-" + that.data.rfId + ",rst=" + res.data.result)
          that.setData({
            hasOrderFlg: true,
            openning_show: true,
            openLockLeaseOptStatus: true,
            equId: res.data.data ? res.data.data.equId : 0,
            opentime: res.data.data ? res.data.data.openTime : '',
            orderCode: res.data.data ? res.data.data.orderCode : '',
          })
          wx.setStorageSync('opentime', res.data.data ? res.data.data.openTime : '');
          wx.setStorageSync('equId', res.data.data ? res.data.data.equId : 0);
          var result = res.data.result;
          if (result == 0) {

            if (res.data.err === "no_pay_deposit") {
              //未交押金
              that.setData({
                callServiceBoxStatus: true,
                openLockLeaseOptStatus: true,
                openning_show: false,
                showModalStatus: false,
                loading_show: false,
                bindUserListStatus: false,
                payDepositStat: false,
                agentLeaseSelStatus: false
              });
              return;
            }

            console.log("租赁成功");
            if (isRedirectOpenLock === true) {
              console.log("租赁成功,直接开锁");
              that.setData({
                openning_desc: '订单生成,准备开锁...',
              })
              that.recordBlueConnectError(ConstantData.err_type.deposit_pay_success_send85, "直接开锁-" + that.data.rfId);
              that.send85Command();
              return;
            }
            var backData = res.data.data;
            if(backData == null) {
              wx.showToast({
                title: '订单已成功',
              })
              that.recordBlueConnectError(ConstantData.err_type.lease_order_repeat, '此设备订单已生成')
              return
            }
            if (that.data.isAllowNoDeposit) {
              wx.setStorageSync("outOrderCode", backData.outOrderCode);
              if (!backData.no_deposit_info) {
                //免押创建订单失败,取消免押的订单，走押金支付
                noDepositLease.noSureCancelOrder(that);
                //免押失败使用交押金租赁
                that.setData({
                  callServiceBoxStatus: true,
                  openLockLeaseOptStatus: true,
                  openning_show: false,
                  showModalStatus: false,
                  loading_show: false,
                  bindUserListStatus: false,
                  payDepositStat: false,
                  agentLeaseSelStatus: false
                });
                return;
              }
              //免押跳转开锁中
              app.globalData.isOpenLock = true;
              console.log("开启免押跳转--->true")
              //隐藏不断开蓝牙
              that.setData({
                hideIsDisconnectStat: false,
                noDepositBackFlg: false,
                openning_desc: '免押授权,页面跳转中(15秒)...',
              })
              that.recordBlueConnectError(ConstantData.err_type.deposit_to_auth, '免押授权,页面跳转中...')

              if (that.data.pt == 'noback') {
                //2019-07-25从使用中的页面扫码进行免押租赁的需要清除pt的标记值，以便免押流程进行
                that.data.pt = '';
              }

              that.data.noDepositCount = 15;
              app.globalData.noDepositTimer = setInterval(() => {
                that.data.noDepositCount = that.data.noDepositCount - 1;
                if (that.data.noDepositCount <= 0) {
                  clearTimeout(app.globalData.noDepositTimer);
                  that.setData({
                    openning_show: false,
                    callServiceBoxStatus: true,
                    hospitalTipBox: false,
                    toPayDeposit: false,

                    hideIsDisconnectStat: true,
                    noDepositBackFlg: true,
                  })
                } else {
                  that.setData({
                    openning_desc: '免押授权,页面跳转中(' + that.data.noDepositCount + '秒)...',
                  })
                }
              }, 1000)

              noDepositLease.toWxNoDepositLeasePage(backData.no_deposit_info, backData.outOrderCode, that);
            } else {
              that.send85Command();
            }
          } else {
            console.log("租赁失败")
            that.setData({
              openning_show: false,
            })
            if ('参数有误1' == res.data.description) {
              //存在未支付订单
              wx.showModal({
                title: '温馨提示',
                confirmText: "去支付",
                content: '存在未支付订单',
                success(res) {
                  if (res.confirm) {
                    // that.toPayOrder()//0717mark--直接吊起收银台
                    wx.navigateTo({
                      url: '../../../pages/user_record/lease/user_lease',
                    })
                  } else if (res.cancel) {
                    console.log('用户点击取消')
                  }
                }
              })

              return;
            }

            if (result == 6000) {
              leaseShow.resultShow('如果确认再次租借')
              return;
            }

            leaseShow.resultShow('租赁失败！' + result + 'Z' + that.data.wxHid)

          }
        },
        fail: function (res) {
          that.recordBlueConnectError(ConstantData.err_type.deposit_created_fail, "生成记录fail-" + that.data.rfId + ';res:' + JSON.stringify(res))

          console.log("租赁失败", res)
          leaseShow.resultShow('服务器忙,请重新扫码 Z' + that.data.wxHid)

        },
        complete: function () {}
      })
    })


  },

  /**
   * 继续租借
   */
  continueToLease() {
    var that = this;
    //继续租赁   
    //将结果值改为正常，用户继续租赁
    that.data.conDevRes.data.rst = 0
    //处理返回数据并调用蓝牙连接
    that.handleConDevRes()
  },
  /**
   * 继续租借
   */
  afterGetDataContinueToLease() {
    var that = this;
    //继续租赁   
    let isBeforeLeaseTip = false;
    that.handleOpenLockData(isBeforeLeaseTip)
  },

  send85Command: function () {    
    var that = this
    clearInterval(that.data.checkPayStatusInterval)
    that.data.openLockLeaseOptStatus = false;
    that.setData({
      loading_show: false,
      openning_show: true,
      openning_desc: '设备正在开锁',
      openLockStat: true
    })
    let connected = getApp().globalData.devConnected;

    if (app.globalData.conBlueVer && app.globalData.conBlueVer == 'om-phy-1.0') {
      that.recordBlueConnectError(ConstantData.err_type.data_76_send, '开始发送phy开锁:' + connected);
      //one more 陪护椅锁开锁指令
      BLELocker.oneMorePhyBleUnlock();
      return;
    }

    if (that.data.isColonyCon) {
      console.log("蓝牙网关开锁处理---->");
      //蓝牙集群连接的
      colonyBlue.openLock(that.data.mac, that);
      that.data.isColonyCon = false;
      return;
    }

    if (that.data.lockSelTypeData) {
      that.recordBlueConnectError(ConstantData.err_type.data_76_send, '开始发送76:' + connected);

      //TODO 发送直行锁命令
      let doorNumArr = that.data.lockSelTypeData.selDoorNumSet;
      if (!doorNumArr || doorNumArr.length == 0) {
        that.recordBlueConnectError(ConstantData.err_type.data_76_fail, "门号信息为空")
      } else {
        that.data.lockSelTypeData = null;
        that.send76Command(doorNumArr[0]);
      }
      return;
    }
    that.recordBlueConnectError(ConstantData.err_type.data_85_send, '开始发送85:' + app.globalData.devConnected);
    //是否正在开锁中
    app.globalData.isOpenLock = true;
    setTimeout(function () {
      that.start85Timer();
      BLELocker.send85Command(function (isSuccess) {
        if (isSuccess == false) {
          that.clear85Timer();
          //重试开锁
          that.retry85('auto');
          let failDesc = app.globalData.devConnected + ";retry85Auto:" + that.data.rfId;
          that.recordBlueConnectError(ConstantData.err_type.data_85_send_fail, (that.data.isRedirectOpenLockFlg ? "redirect:" : "开始开锁-fail") + failDesc);
        } else {
          that.recordBlueConnectError(ConstantData.err_type.data_85_send_suc, (that.data.isRedirectOpenLockFlg ? "redirect:" : "开始开锁-suc") + that.data.rfId)
        }
      })
    }, 500);


  },
  send75Command: function (params) {
    var that = this;
    //发送75命令获取信息
    BLELocker.send75Command(function (isSuccess) {
      if (isSuccess == false) {
        if (params == '00') {
          that.connectBLEDevice(that.data.curBlueName)
        } else {
          wx.showModal({
            showCancel: false,
            title: '温馨提示',
            content: '通信失败,请扫码重试',
            success(res) {}
          })
        }
      } else if (isSuccess == "recevieTimeout") {
        that.handleStatus(BLELocker.Status.bleRecive75Timeout);
      }
    }, params);
  },

  start85Timer: function () {
    let that = this;
    that.clear85Timer();
    that.setData({
      openLockLeftSeconds: 20
    })
    that.data.timer_85_seconds = setInterval(() => {
      if (!app.globalData.devConnected && that.data.isRetry85) {
        that.setData({
          openning_show: false
        })
        //蓝牙断开
        that.clear85Timer();
        BLELocker.stop85Back1Timeout();
        BLELocker.stop85Back2Timeout();
        //重试开锁
        that.retry85('auto');
      } else if (that.data.openLockLeftSeconds == 0) {
        let pile_id = that.data.pile_id ? 'Z' + that.data.pile_id : '';
        let descMini = pile_id + '-' + ConstantData.err_type.data_85_send_timeout;
        statistic.noEjectDialog(that, descMini);
        that.recordBlueConnectError(ConstantData.err_type.data_85_timer, '20秒的85计时器计时结束，弹出未弹出提示')
        return
      }
      that.setData({
        openLockLeftSeconds: that.data.openLockLeftSeconds - 1
      })
    }, 1000)
  },
  /*开锁成功之后的回调*/
  clear85Timer: function () {
    let that = this;
    clearInterval(that.data.timer_85_seconds);
    that.data.timer_85_seconds = null;
  },

  /**
   * 重试95
   */
  retry95() { // mark: 重试95
    console.log("重试读取95数据----")
    let that = this
    if (that.data.trying) {
      return
    }
    that.data.trying = true
    setTimeout(() => {
      that.data.trying = false
    }, 3000)
    console.log("重试读取95数据----aaa")
    connectShow.read();
    console.log("重试读取95数据----bbb")
    that.data.retry95Flg = true;
    this.send95Command();
  },

  send95Command: function () { // mark: 重试发送95命令
    var that = this;
    //重试发送95的标记
    that.data.retry95Flg = true;
    if (!that.data.randomNum) {
      that.data.randomNum = app.globalData.boxRandomNumKey;
    }
    if (!getApp().globalData.devConnected) {
      that.handleConDevRes()
    } else if (that.data.randomNum) {
      BLELocker.send95Command(function (isSuccess) {
        if (isSuccess == false) {
          that.connectBLEDevice(that.data.curBlueName)
        } else if (isSuccess == "recevieTimeout") {
          that.handleStatus(BLELocker.Status.bleRecive95Timeout);
        }
      })
      return;
    } else {
      leaseShow.resultShow('请重新扫码租借!')
    }
  },

  //展示连接状态信息  
  showStatInfo: function (stat) {
    console.log("展示租赁相关状态信息:", stat)
    let that = this
    if (stat == that.data.statVal.queryNoDeposit) {
      connectShow.noDepositOrderCheck()
    } else if (stat == that.data.statVal.noDepositOpen) {
      connectShow.noDepositOpenShow()
    } else if (stat == that.data.statVal.discover) {
      connectShow.discover()
    }
  },
  //错误提示信息确定点击事件
  modalTipClick: function () {
    conTimer.clearConTimer()
    wx.navigateBack({
      delta: 1
    })
  },
  // // mark: 确认已弹出
  sucOpenConfirm: function () {
    let that = this;
    conTimer.clearConTimer()
    that.data.openLockStat = false; //当前已开锁完毕
    that.data.hasOrderFlg = false;
    if (!that.data.equId || !that.data.opentime) {
      that.data.equId = wx.getStorageSync('equId');
      that.data.opentime = wx.getStorageSync('opentime');
    }
    wx.redirectTo({
      url: '../../../pages/index/lease_tip/lease_tip?pt=lease&equId=' + that.data.equId + "&opentime=" + that.data.opentime + '&lockType=' + that.data.lockType,
    })
  },
  // mark: 归还成功提示
  backSuc: function () {
    let that = this
    let data = that.data.backDataInfo
    wx.navigateTo({
      url: '../../../pages/index/lease_tip/lease_tip?pt=back&equId=' + data.eqId + "&rent=" + data.rent + "&backtime=" + data.backTime + "&opentime=" + data.openTime + "&costtime=" + data.timeLenStr + "&depositBackSuc=" + data.isAutoRefund +
        '&lockType=' + that.data.lockType + '&backSucDesc=' + data.backSucDesc + '&backSucVoiceUrl=' + data.backSucVoiceUrl,
    });
  },
  // mark: 重试开锁
  retry85: function (retryType) {
    var that = this;
    connectShow.openLockingShow()
    that.data.canRetry85 = true;
    that.data.hasOrderFlg = false;
    that.data.no_eject_back_flg = null;
    that.data.retryType85 = retryType;
    if (retryType == 'auto') {
      let desc = app.globalData.devConnected ? "蓝牙未断开,开锁失败,重试开锁" : "开锁时蓝牙断开，自动重新连接开锁";
      that.recordBlueConnectError(ConstantData.err_type.data_85_discon_retry, desc);
    } else {
      let desc = app.globalData.devConnected ? "蓝牙未断开,开锁失败,点击重试开锁" : "开锁时蓝牙断开，用户点击重试租借，重新连接";
      that.recordBlueConnectError(ConstantData.err_type.data_85_retry, desc);
    }
    that.clear85Timer();
    BLELocker.stop85Back1Timeout();
    BLELocker.stop85Back2Timeout();
    if (app.globalData.devConnected) {
      that.recordBlueConnectError(ConstantData.err_type.data_85_send, '开始发送85重试:' + app.globalData.devConnected);
      BLELocker.send85Command();
    } else {
      setTimeout(() => {
        that.connectBLEDevice(that.data.curBlueName);
      }, 800)
    }
  },
  //去支付押金 
  toPayDeposit: function (event) {
    var that = this

    if (!that.data.read) {
      wx.showToast({
        title: '请勾选我已阅读'
      })
      return
    }
    if (!this.data.payDepositBtnStatus) {
      return;
    }
    console.log("去支付。。。equTid=", that.data.equId)

    that.data.payDepositBtnStatus = false

    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_dposit/wxmini/to_pay',
        method: 'post',
        header: header,
        data: {
          eqId: that.data.equId,
          mac: that.data.conMac
        },
        success: function (res) {
          console.log('/lease_dposit/wxmini/to_pay----->', res)
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          var data = res.data
          if (data.result == 0) {
            that.toPay(data.data)
          } else if (data.result == -1) {
            wx.navigateTo({
              url: '../../../pages/user_record/deposit/user_deposit',
            })
          } else {
            that.setData({ // mark: 弹框去缴纳押金
              alertBoxStatus: true,
              alertBoxTipContent: data.description,
              payDepositBtnStatus: true,
              payDepositBtnTxt: "去缴纳"
            })
          }

        },
        fail: function () {
          that.setData({
            payDepositBtnStatus: true,
            payDepositBtnTxt: "去缴纳"
          })
        }
      })

    })
  },

  payDepositSuccess() {
    var that = this

    if (that.data.checkPayStatusInterval) {
      clearInterval(that.data.checkPayStatusInterval);
    }
    that.setData({
      checkPayStatusInterval: null,
    });

    that.recordBlueConnectError(ConstantData.err_type.deposit_pay_confirm, "[押金]支付成功")
    that.getSubscribeMessage('押金支付成功', function () {
      connectShow.payDepositOpenShow()
      wx.setStorageSync("no_pay_deposit", 0);
      that.recordBlueConnectError(ConstantData.err_type.deposit_pay_success, '押金支付成功,准备开锁...');
      if (that.data.noDepositFail) {
        that.setData({
          noDepositFail: false
        })
      }

      if (that.data.isColonyCon) {
        //网关开锁前标记，在断开连接时进行判断是否
        app.globalData.gatewayUnlockFlg = true;
        //网关开锁前标记的时间点，判断断开时校验时间，如果超过30秒，则认为标记失效进行断开
        app.globalData.gatewayUnlockFlgTime = new Date().getTime();
        that.recordBlueConnectError(ConstantData.err_type.deposit_pay_success_openlock, "[开锁]gateway开始直接开锁-押金支付成功");
        that.leaseEquipment(true);
        return;
      }

      //判断是否还在连接，连接着的直接开锁进行租赁
      wx.getConnectedBluetoothDevices({
        services: ['FEE7'],
        success: function (res) {
          console.log("111----current connected blue " + JSON.stringify(res))
          if (res.devices && res.devices.length > 0) {
            //展示收费规则提示框
            that.setData({
              payDepositStat: true,
              showModalStatus: false,
              mapShowStatus: false,
              hideIsDisconnectStat: false,
              bindUserListStatus: false,
              agentLeaseSelStatus: false,
              isPayDeposit: true
            })
            that.recordBlueConnectError(ConstantData.err_type.deposit_pay_success_openlock, "[开锁]开始直接开锁-押金支付成功");
            that.leaseEquipment(true);
          } else {
            that.data.bleDepositPaySuc = true;
            that.recordBlueConnectError(ConstantData.err_type.deposit_pay_success_connect, "[连接]没有设备,重新连接-押金支付成功")
            connectCurrentBlue(that)
          }
        },
        fail: function () {
          that.data.bleDepositPaySuc = true;
          that.recordBlueConnectError(ConstantData.err_type.deposit_pay_success_reconnect, "[连接]获取失败,重新连接-押金支付成功")
          connectCurrentBlue(that)
        }
      })
    });
  },

  toPay: function (orderCode) {
    var that = this
    console.log("去支付。。。" + orderCode);

    app.toPayValideLogin(orderCode, function (loginCode, orderCode, err) {

      app.executeRequest(function (header) {

        wx.request({
          url: ConstantData.CONSTATNT_DATA.BASE_URL + '/ejiam/wxmini/weixin/pay',
          method: 'post',
          header: header,
          data: {
            orderCode: orderCode,
            loginCode: loginCode,
            wxErr: err
          },

          success: function (res) {
            let netErr = app.handleRes(res, that);
            if (netErr) {
              return
            }
            var data = res.data
            console.log("支付结果---" + data.result)
            if (data.result != 0 || !data.data || !data.data.timeStamp) {
              leaseShow.resultShow(data.description ? data.description : '押金支付失败')
              that.recordBlueConnectError(ConstantData.err_type.deposit_pay_fail, '押金支付请求失败')
              return
            }

            app.globalData.isOpenLock = true;
            that.setData({
              hideIsDisconnectStat: false, //支付成功后隐藏不关闭蓝牙
              openning_show: true, //200114 冯慧敏，押金支付之前就显示开锁中，以防止押金支付成功后用户有机会再次点击扫码，影响开锁
              openning_desc: '正在支付押金...',
            })

            if (that.data.checkPayStatusInterval) {
              clearInterval(that.data.checkPayStatusInterval);
            }
            that.data.isPayDepositSuccess= false;
            that.data.checkPayStatusInterval = setInterval(() => {
              console.log('【轮询押金支付状态】');
              if (that.data.isPayDepositSuccess) {
                clearInterval(that.data.checkPayStatusInterval);
                that.data.checkPayStatusInterval= null
                return;
              }

              noDepositLease.queryPayDepositStatus(orderCode).then(res => {
                console.log('【押金支付状态查询】已支付...' + res);
                that.data.isPayDepositSuccess= true;
                that.payDepositSuccess();
                clearInterval(that.data.checkPayStatusInterval)
              }).catch(error => {
                console.log('【押金支付状态查询】未支付...' + error);
              })

            }, 1000);        

            wx.requestPayment({
              appId: 'wx0e458dc331e557cc',
              timeStamp: data.data.timeStamp,
              nonceStr: data.data.nonceStr,
              package: data.data.package,
              signType: data.data.signType,
              paySign: data.data.paySign,
              success: function (res) {
                if (that.data.isPayDepositSuccess) {
                  that.getSubscribeMessage('押金支付成功', null);
                  return;
                }
                that.payDepositSuccess();
              },
              fail: function (res) {
                app.globalData.isOpenLock = false;
                that.recordBlueConnectError(ConstantData.err_type.deposit_pay_cancel, "押金FAIL:" + JSON.stringify(res))
                that.setData({
                  openning_show: false,
                  hideIsDisconnectStat: false,
                  payDepositBtnStatus: true,
                  payDepositBtnTxt: "去缴纳"
                })
                common.recordErrorInfo(ConstantData.err_type.pay_fail, res ? 'index2-' + JSON.stringify(res) : '');

                if (that.data.checkPayStatusInterval) {
                  clearInterval(that.data.checkPayStatusInterval);
                }
              },
              complete: function (res) {
                that.setData({
                  hideIsDisconnectStat: false,
                  payDepositBtnStatus: true,
                  payDepositBtnTxt: "去缴纳"
                })
                console.log("complete--" + data.data.paySign)
                console.log(res)

                if (that.data.checkPayStatusInterval) {
                  clearInterval(that.data.checkPayStatusInterval);
                }
              }
            })


          }
        })

      })

    });

  },

  getSubscribeMessage: function (text, callback) {
    if (wx.requestSubscribeMessage) {
      console.log('【订阅消息】支持弹出订阅消息...')
      let tmplIds = ['KnUsFuS2NB07Pf9xbznQlyK_qZOU7DxOFl8l6E26Nww', '-S91jtVpX2Vto5EyXauKW008LYSSbsZiI8IWdepDarE'];
      let acceptIds = [];
      wx.requestSubscribeMessage({
        tmplIds: tmplIds,
        success(res) {
          console.log('【订阅消息】弹出订阅消息成功...' + JSON.stringify(res))
          let acceptIds = [];
          for (let i = 0; i < tmplIds.length; i++) {
            res[tmplIds[i]] == 'accept' ? acceptIds[i] = 1 : acceptIds[i] = 0;
          }
          app.executeRequest((header) => {
            wx.request({
              url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_user/wx_sub_msg',
              method: 'post',
              header: header,
              data: {
                acceptIds: JSON.stringify(acceptIds)
              }
            })
          })
        },
        fail(error) {
          console.log('【订阅消息】弹出订阅消息失败...' + JSON.stringify(error))
        },
        complete(res) {
          console.warn('【订阅消息】弹出订阅消息完成...' + text, res, acceptIds);
          if (callback) {
            callback();
          }
        }
      })
    } else {
      console.log('【订阅消息】不支持弹出订阅消息...')
      if (callback) {
        callback();
      }
    }
  },
  //其他页面调用失败信息
  showFailTip: function () {
    bleFailShow.modalMsgShow()
  },

  switchRulesShow() {
    this.setData({
      showRules: !this.data.showRules
    })
  },

  /**
   * 选择包时卡绑定账号的变更
   */
  bindUserChange: function (e) {
    var val = e.detail.value
    var user = this.data.bindUserList[val[0]]

    console.warn(user)

    if (!user.bindUid) {
      wx.showToast({
        title: '请重新选择',
      })
      return
    }

    this.setData({
      user_tab: user.bindTag,
      selBindUserId: user.bindUid,
      checkboxStatus: 'checkboxSelected',
      selBindUser: user
    })
  },
  /**
   * 绑定包时卡的账号确定开锁
   */
  bindUserChangeSure: function () {
    if (this.data.selBindUserId == 0) {
      this.setData({
        selBindUserId: this.data.bindUserList[0].bindUid,
        selBindUser: this.data.bindUserList[0]
      })
    }

    this.setData({
      agentLeaseSelStatus: false,
      isPayDeposit: true,
    })

    var selBindUid = this.data.selBindUserId
    console.log("代租赁,开始开锁------")
    console.log(selBindUid)

    this.openLock()
  },
  /**
   * 绑定包时卡账号取消选择
   */
  cancelAgentLease: function () {
    app.globalData.isConnecting = false;
    BLELocker.disconnect('index1032')
    this.setData({
      agentLeaseSelStatus: false,
      bindUserListStatus: false,
      mapShowStatus: true,
    })
  },
  /**
   * 确定租赁
   */
  sureToAgentLease: function () {
    this.setData({
      cancelAgentSelLeaseStatus: false,
      isPayDeposit: true
    })

    var that = this
    var selBindUid = this.data.selBindUserId
    var selUser = this.data.selBindUser
    if (selBindUid == 0) {
      selUser = this.data.bindUserList[0]
    }
    //绑定类型2爱心租赁，1包时卡租赁
    var bindType = 1
    var timeLenStr = ''
    if (selUser.employerUid) {
      //爱心租赁的
      bindType = 2
    } else {
      //绑卡代租的
      bindType = 1
    }

    var eqTid = this.data.wxEqTid
    console.log("确认完选择的代租用户--" + eqTid + "," + selUser.bindUid)
    this.validateBindNoPayOrNoReturn(selUser, eqTid, bindType)
  },
  /**
   * 校验包时卡或门诊爱心租赁是否存在未支付或未归还的
   */
  validateBindNoPayOrNoReturn: function (selUser, eqTid, bindType) {
    var that = this

    var cardTimeLen = selUser.cardTimeLen
    var timeLenStr = this.data.leftTimeLenStr
    var noPayStrSuffix = ''
    if (bindType == 1) {
      //包时卡的时长信息
      timeLenStr = selUser.bindPhone + '(' + selUser.bindTag + '),剩余时长:'
      if (cardTimeLen < 60) {
        timeLenStr += cardTimeLen + '分钟'
      } else {
        timeLenStr += parseInt(cardTimeLen / 60) + '小时'
      }

      noPayStrSuffix = ',请电话告知用户购买包时卡后才能再借用!'
    } else if (bindType == 2) {
      noPayStrSuffix = ',请完成支付再租借!'
    }

    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_time_card/nopay',
        method: 'post',
        header: header,
        data: {
          buid: selUser.bindUid,
          tid: eqTid,
          bindType: bindType
        },
        success: function (res) {
          console.log(res)
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          var result = res.data.data
          var noPayTimeLen = result.noPayTimeLen
          var noReturnCount = result.noReturnCount
          var depositPayRst = result.depositPayRst
          var cardTimeLen = result.cardTimeLen
          var noReturnEquId = result.noReturnEquId
          var equTypeName = result.equTypeName
          var isCouldLease = true
          var noPayTipStatus = false
          var noPayTimeLenStr = ''
          var noLeaseTipInfo = ''
          if (cardTimeLen <= 0 && bindType == 1) {
            //包时卡时间不足
            isCouldLease = false
            noPayTipStatus = true
            noLeaseTipInfo = '包时卡已用完，不能为他(代租)，请电话通知家属购买包时卡'
          } else if (depositPayRst <= 0) {
            //未交押金
            isCouldLease = false
            noPayTipStatus = true
            noLeaseTipInfo = '该用户押金还未支付,不能租借'
          } else if (noReturnEquId > 0) {
            //存在未归还设备
            noLeaseTipInfo = '该用户有租借的' + noReturnEquId + '号' + equTypeName + '没有归还,不能租借'
            isCouldLease = false
            noPayTipStatus = true
          } else if (noPayTimeLen && noPayTimeLen > 0) {
            //存在未支付的订单
            isCouldLease = false
            noPayTipStatus = true
            if (noPayTimeLen < 60) {
              noPayTimeLenStr = noPayTimeLen + '分钟'
            } else {
              noPayTimeLenStr = parseInt(noPayTimeLen / 60) + '小时'
            }
            noLeaseTipInfo = '该用户已欠费(有' + noPayTimeLenStr + '时长未付款)' + noPayStrSuffix
          } else {
            //可以正常租赁
          }

          that.setData({
            selBindUserId: selUser.bindUid,
            user_tab: selUser.bindTag,
            leftTimeLenStr: timeLenStr,
            agentLeaseSelStatus: true,
            showModalStatus: false,
            bindUserListStatus: false,
            mapShowStatus: false,
            leaseBtnStatus: isCouldLease,
            noPayTimeTipStatus: noPayTipStatus,
            noPayTimeLenStr: noPayTimeLenStr,
            noLeaseTipInfo: noLeaseTipInfo
          })
        },
        fail: function (res) {
          wx.showToast({
            title: '稍后重试',
          })
        }
      })

    })

  },
  goUserLease: function () {
    wx.navigateTo({
      url: '/pages/user_record/lease/user_lease',
    })
  },
  /**
   * 跳转到关注公众号的页面
   */
  goFollowMp: function () {
    app.goFollowMp(-200002, '关注公众号-我的')
  },
  /**
   * 继续租借
   */
  continueToLease() {
    var that = this;
    //继续租赁   
    //将结果值改为正常，用户继续租赁
    that.data.conDevRes.data.rst = 0
    //处理返回数据并调用蓝牙连接
    that.handleConDevRes()
  },

  /**
   * 网络异常
   */
  networkFail() { // mark: 网络断开提示
    BLELocker.disconnect('networkFail3676');
    leaseShow.netFail("网络断开，请检查网络后，重新扫码")
  },

  /**
   * 重新扫码
   */
  reScan: function () {
    let that = this
    that.data.bleDepositPaySuc = false;

    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        that.data.isWxScanFlg = false;
        var qrc = '';
        var qrCode = res.result;
        if (!qrCode) {
          wx.showToast({
            title: '二维码为空',
          })
          that.recordBlueConnectError(ConstantData.err_type.qrc_null, "二维码为空,qrc=" + qrCode)
          that.data.scanningCode = false;
          return;
        }
        let macReg = /[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}/;
        let isMacAddr = macReg.test(qrCode);
        if (qrCode.indexOf(ConstantData.CONSTATNT_DATA.DEVICE_QRCODE_URL_PREFIX) == 0 || isMacAddr) {
          //设备二维码
          let qrc_old = app.getScanQrcContent();
          that.data.qrcContent = qrCode;
          if (isMacAddr) {
            qrc = qrCode.replace(/:/g, "");
          } else {
            var rst = qrCode.split('/');
            qrc = rst[rst.length - 1];
            that.data.qrc = qrc;
          }
          app.globalData.scan.qrc = qrc;
          try {
            wx.setStorageSync('scan_qrc', qrc);
          } catch (e) {}
          if (qrc != qrc_old) {
            wx.removeStorageSync('blue_fail_time')
            wx.removeStorageSync('rfid_error_time')
            wx.removeStorageSync('insert_fail_time')
            wx.removeStorageSync('hook_fail_time')
            wx.removeStorageSync('has_opened_gprs')
            wx.removeStorageSync('no_eject_times')
          }
        } else {
          leaseShow.resultShow('二维码扫描异常，请换一个桩租赁');
          that.data.scanningCode = false;
          that.recordBlueConnectError(ConstantData.err_type.qrc_err, "二维码有误,qrc=" + qrCode)
          return
        }
        console.log("scan-----------qrc=" + qrc)
        console.log("******获取要连接的设备名称", app.globalData.conTimeoutTimer, !null);

        that.getDevIdAndConnect(qrc, 'scan');

      },
      fail: function (res) {
        that.data.scanningCode = false;
        that.setData({
          loading_show: false
        })
        that.data.qrcContent = '';
        that.recordBlueConnectError(ConstantData.err_type.qrc_cancel, "调用微信扫码失败或取消")
      }
    });

  },

  // mark: 重新连接
  retryConnect: function () {
    connectShow.reday()
    this.connectBLEDevice(this.data.curBlueName);
  },

  //记录归位桩蓝牙连接错误日志
  recordBlueConnectError: function (errType, errDesc, tag) {
    var that = this
    let nowTime = util.formatTime(new Date()) + '-----';
    var miniVer = ConstantData.CONSTATNT_DATA.MINI_VERSION
    let authStr = systemInfo ? (systemInfo.locationAuthorized + ',' + systemInfo.bluetoothEnabled + ',' + systemInfo.locationEnabled + ',' + systemInfo.wifiEnabled) : 'null'
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/error/bc',
        method: 'post',
        header: header,
        data: {
          homingPileBlueName: that.data.curBlueName, //归位桩的蓝牙名称,最长100个字
          phoneOs: systemInfo.system, //手机系统信息,最长245
          phoneFactory: systemInfo.model, //手机厂商,最长245
          phoneType: systemInfo.model || systemInfo.brand, //手机型号,最长245
          weixinVer: systemInfo.version + ',' + baseVer + ',' + miniVer, //微信版本号,最长45
          errType: errType ? parseInt((errType + '').replace(/[^0-9]/ig, '')) : -1, //错误类型,最大值127；1.搜索,2.连接,3.auth,4.init 5. 95 6. 85
          errDesc: nowTime + '[' + authStr + ']' + ',' + errDesc + ',', //错误描述,最长545
          tag: tag && tag != 'undefined' ? tag : ''
        },
        success: function (res) {
          console.log("recordErrSuc", res)
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }
          // console.log("蓝牙连接错误日志记录成功", errDesc);
        },
        fail: function (res) {
          // console.log("蓝牙连接错误日志记录失败")
          console.log("recordErrFail", res)
        }
      })
    })
  },
  //客服中心
  toService:function(){
    wx.switchTab({
      url:'/pages/servicer/index'
    })
  },
  //故障上报
  tofault:function(){
    wx.navigateTo({
      url: '/pkgNew/pages/faultReporting/index',
    })
  }
})

//租赁相关的展示提示
var leaseShow = { // mark: 租借信息展示对象
  //页面数据操作对象 
  pageThat: null,
  //收费规则
  chargeRuleShow: function () {    
    let freeTimeTipContent = this.pageThat.data.leftFreeTimeTipContent
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      leaseBtnShow: true,
      showStat: {
        rule: true
      },
      leftFreeTimeTipContent: freeTimeTipContent,
      showFreeTipDialog: freeTimeTipContent ? true : false
    })
    console.log("showFreeTipDialog-->", this.pageThat.data.showFreeTipDialog)
  },
  //开锁成功显示
  openSucShow: function () {
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        leasesuc: true
      }
    })
  },
  //开锁失败显示
  openFailShow: function () {
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        failTip: true
      }
    })
  },
  //归还成功显示
  backSucShow: function () {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        resultTip: true,
        backSucBtn: true,
        resultDesc: '您已完成归还！',
        resultSecondDesc: '如需要租借点击首页"扫码开锁"按钮',
      }
    })
    //播放归还成功语音
    console.log("播放归还成功语音")
    AudioUtil.play('/image/backSuc.mp3', false) 
  },
  //帮归还成功显示
  helpBackSucShow: function () {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        resultTip: true,
        helpBackSucBtn: true,
        resultDesc: '您已帮忙归还成功！',
        resultSecondDesc: '若您需要租借，点击"扫码开锁"按钮',
      }
    })
  },
  //归还失败显示
  backFailShow: function () {

  },
  //用户归还后立马再次租借提醒
  backSucToLeaseTip: function () {
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        backSucToLease: true
      }
    })
  },
  //租赁前消息提示
  beforeLeaseTipShow: function (continueLeaseBtnLeft, contintueLeaseBtnName, cancelBtnName, tipContent) {
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        beforeLeaseTip: true,
        continueBtnLeft: continueLeaseBtnLeft,
        cancelBtnName: cancelBtnName,
        continueBtnName: contintueLeaseBtnName,
        tipContent: tipContent
      }
    })
  },
  openLockOverTip: function () {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    console.log("开锁完成广告：", app.globalData.miniBeeConfig, app.globalData.miniBeeConfig.lease_success)
    this.pageThat.setData({
      connectType: '租借',
      showStat: {
        blankBtn: false,
        resultTip: true,
        openOverConfirm: true,
        resultDesc: '开锁完成',
      },
      beeBannerConfig: app.globalData.miniBeeConfig.lease_success
    })
    console.log("开锁完成播报语音")
    //播放租借成功语音
    AudioUtil.play('/image/leaseLinkSuc.mp3', false) 
  },
  //结果提示
  resultShow: function (resultDesc) {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      leaseBtnShow: false,
      showStat: {
        resultTip: true,
        resultDesc: resultDesc,
        blankBtn: true
      }
    })
  },
  //结果显示取消
  resultHide: function () {
    this.pageThat.setData({
      showStat: {
        resultTip: false
      }
    })
  },

  //网络fail提示
  netFail: function (desc) {
    this.resultShow(desc)
  }
}

//蓝牙权限相关提示
var bleAuthShow = { // mark: 蓝牙授权信息展示对象
  //页面数据操作对象
  pageThat: null,
  //安卓系统蓝牙可跳转到设置页的
  showAndroidToSettingBle: function (that) {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        bleauthAndroidToSet: true
      }
    })
  },
  //安卓系统设置系统蓝牙的方式
  showAndroidSetTip: function (that) {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        bleauthAndroid: true
      }
    })
  },
  //IOS系统设置系统蓝牙的方式
  showIosSetBleTip: function (that) {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        bleauthIos: true
      }
    })
  },
  //安卓系统定位权限配置提示
  showAndroidSysLocationSetting: function (that) {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        locationAndroidTip: true
      }
    })
  },
  //Ios系统定位权限配置提示
  showIosSysLocationSetting: function (that) {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        locationIosTip: true
      }
    })
  },
  //IOS的app蓝牙配置项
  showAppBleSetting: function (that) {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        bleauthAppToSet: true
      }
    })
  },
  //Ios应用定位权限配置提示
  showAppLocationSetting: function (that) {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        locationAuthAppToSet: true
      }
    })
  },

  //小程序蓝牙权限未授权
  showBleMiniToSet: function (that) {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        bleMiniAuthToSet: true
      }
    })
  },


}

var connectShow = { // mark: 连接提示信息展示对象
  //页面数据操作对象
  pageThat: null,
  //连接准备开始    
  reday: function () {
    conTimer.start()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        connect: true,
        conStatDesc: "连接信息检查中...",
      }
    })
  },
  //蓝牙权限
  checkBle: function () {
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        connect: true,
        conStatDesc: "蓝牙权限检查中...",
      }
    })
  },
  //连接开始
  start: function () {
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        connect: true,
        conStatDesc: "连接中...",
      }
    })
  },
  //搜索中
  discover: function () {
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        connect: true,
        conStatDesc: "查找设备中,请稍后...",
      }
    })
  },
  //开启连接
  connect: function () {
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        connect: true,
        conStatDesc: "连接成功,数读取中...",
      }
    })
  },
  //读取数据及解析数据
  read: function () {
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        connect: true,
        conStatDesc: "连接成功,数读取中...",
      }
    })
  },
  //免押查询
  noDepositOrderCheck: function () {
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        connect: true,
        conStatDesc: "免押信息核对中...",
      },
      leaseBtnShow: false,
    })
  },
  noDepositOpenShow: function () {
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        connect: true,
        conStatDesc: "免押授权成功,准备开锁...",
      },
      leaseBtnShow: false,
    })
  },
  payDepositOpenShow: function () {
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        connect: true,
        conStatDesc: "押金支付成功,准备开锁...",
      },
      leaseBtnShow: false,
    })
  },
  //开锁中
  openLockingShow: function () {
    conTimer.start(15)
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        connect: true,
        conStatDesc: "开锁中...",
      },
      leaseBtnShow: false,
    })
  },
  networkConnecting: function () {
    conTimer.start()
    this.pageThat.hideAllShow()
    let extParams = this.pageThat.data.conDevExtParams
    let gatewayId = extParams ? "(" + extParams.gatewayId + ")" : ""
    this.pageThat.setData({
      showStat: {
        connect: true,
        conStatDesc: "网关" + gatewayId + "连接中...",
      }
    })
  },
  //接收到95数据开始处理
  handle95Data: function () {
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        connect: true,
        conStatDesc: "数据已返回,开始处理...",
      }
    })
  },
  //上报95数据
  getRuleOrBack: function () {
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      showStat: {
        connect: true,
        conStatDesc: "请稍等,处理数据中...",
      }
    })
  }
}

//蓝牙连接过程失败
var bleFailShow = {
  //页面数据操作对象
  pageThat: null,
  showMsg: function (msg) {
    conTimer.clearConTimer()
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      leaseBtnShow: false,
      showStat: {
        connect: true,
        msg: msg,
      }
    })
  },
  modalMsgShow: function () {
    this.pageThat.hideAllShow()
    this.pageThat.setData({
      leaseBtnShow: false
    })
    conTimer.clearConTimer()
  },
  openFailTipShow: function (errType) {
    this.modalMsgShow()
    let pile_id = this.pageThat.data.pile_id ? 'Z' + this.pageThat.data.pile_id : '';
    this.pageThat.setData({
      modal: {
        modal_show: true,
        desc: '1、如未弹出，请点击“重试租借”再租借一次，\n2、如已弹出，请点击“设备已弹出”。\n3、请慎重选择，如果不做操作，我们将默认为设备已弹出。',
        desc_mini: pile_id + '-' + (errType ? errType : ''),
        desc_center: false,
        sucOpen: true,
        retry85: true
      }
    })
  }
}
// mark: 连接计时器
var conTimer = {
  //页面数据操作对象
  pageThat: null,
  conTimeCount: null,
  start: function (seconds) {
    let pthat = this.pageThat
    let conThat = this
    console.log("连接倒计时定时器--->");
    pthat.setData({
      conLeftSeconds: seconds ? seconds : 60
    });
    if (this.conTimeCount != null) {
      clearInterval(this.conTimeCount);
    }
    this.conTimeCount = setInterval(() => {
      let leftSecond = pthat.data.conLeftSeconds - 1;
      console.log("connnect -->leftSecond=", leftSecond);
      if (leftSecond <= 0) {
        clearInterval(conThat.conTimeCount);
        if (!pthat.data.leaseBtnShow) {
          //倒计时结束未连接成功
          BLELocker.disconnect('condev4108');
          if (pthat.data.curContIsBle) {
            leaseShow.resultShow("连接超时，请重新扫码租借")
          }
        }
      } else {
        pthat.setData({
          conLeftSeconds: leftSecond
        });
        if (pthat.data.curContIsBle && leftSecond < 35) {
          //检查当前权限是否存在异常，导致超时
          pthat.bleConAuthCheck(false)
        }
      }
    }, 1000);
  },
  //清空连接的计时器
  clearConTimer: function () {
    clearInterval(this.conTimeCount);
    if (app.globalData.conTimeoutTimer) {
      clearTimeout(app.globalData.conTimeoutTimer)
    }
    if(app.globalData.scanEquTimer) {
      clearTimeout(app.globalData.scanEquTimer)
    }
  },


}

/**
 * 获取新连接错误标记的错误码
 */
function getTimeoutReasonCode() {
  let errDesc = app.globalData.conErrDesc;
  let errCode = '10030';
  if (errDesc) {
    if (errDesc.indexOf('搜索超时') != -1) {

      errCode = '10034';
    } else if (errDesc.indexOf('openAdapterTimeout') != -1) {
      errCode = '100312';
    } else if (errDesc.indexOf('locationAuthTimeout') != -1) {
      errCode = '100313';
    } else if (errDesc.indexOf('openBluetoothAdapter') != -1) {
      let systemInfo = wx.getStorageSync('systeminfo');
      if (systemInfo.system.toLowerCase().indexOf('ios 13') != -1) {
        errCode = '100310';
      } else {
        errCode = '10031';
      }
    } else if (errDesc.indexOf('getBluetoothDevices') != -1) {
      errCode = '10032';
    } else if (errDesc.indexOf('startBluetoothDevicesDiscovery') != -1) {
      errCode = '10033';
    } else if (errDesc.indexOf('createBLEConnection') != -1) {
      errCode = '10035';
    } else if (errDesc.indexOf('getBLEDeviceServices') != -1) {
      errCode = '10036';
    } else if (errDesc.indexOf('getBLEDeviceCharacteristics') != -1) {
      errCode = '10037';
    } else if (errDesc.indexOf('notifyBLECharacteristicValueChanged') != -1) {
      errCode = '10038';
    } else if (errDesc.indexOf('receivingData') != -1) {
      errCode = '10039';
    }
  }
  return errCode;
}

function getBLETimeoutReasonType(that) {
  //判断特殊机型
  let blue_fail_time = wx.getStorageSync('blue_fail_time') || 1;
  wx.setStorageSync('blue_fail_time', blue_fail_time + 1);
  let user_no_back = wx.getStorageSync('user_no_back');
  let errType = '';
  let pile_id = that.data.pile_id ? 'Z' + that.data.pile_id : '';

  if (user_no_back) {
    //判断次数
    if (blue_fail_time > 2) {
      errType = 100346;
      var desc = "未找到扫码的桩,请确认设备已经锁好且拉不下来后可联系客服帮您归还。";
      var desc_mini = 'STO搜索不成功,请确保设备' + pile_id + '在您附近(' + that.data.phoneInfo + '-100346)';
      var contact = true
      var confirm = false
    } else {
      errType = 100345;
      var desc = "未找到扫码的桩,请关闭蓝牙再打开后重试";
      var desc_mini = 'STO搜索不成功,请确保设备' + pile_id + '在您附近(' + that.data.phoneInfo + '-100345)';
      var contact = false
      var confirm = true
    }
    that.setData({
      modal: {
        modal_show: true,
        desc: desc,
        desc_mini: desc_mini,
        contact: contact,
        confirm: confirm,
      }
    })
  }

  if (errType) {
    that.recordBlueConnectError(errType, 'modalErr:连接超时');
  }
}

function connectCurrentBlue(that) {
  //隐藏可以关闭蓝牙
  that.data.hideIsDisconnectStat = true;
  if (that.data.curBlueName) {
    connectShow.reday()
    that.connectBLEDevice(that.data.curBlueName)
  } else {
    leaseShow.resultShow('请重新扫码!')
  }
}